简单函数¶
一组简单的函数。
函数
- binary_search(function, target, lower_bound, upper_bound, tolerance=0.0001)[来源]¶
通过反复将范围分成两半来在范围内搜索值。
更准确地说,执行数值二分搜索以确定在给定边界之间的
function的输入,该输入输出target在tolerance(默认值为0.0001)范围内。如果在边界内找不到输入,则返回None。示例
考虑多项式 \(x^2 + 3x + 1\),我们寻找目标值 \(11\)。一个精确解是 \(x = 2\)。
>>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5) >>> abs(solution - 2) < 1e-4 True >>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5, tolerance=0.01) >>> abs(solution - 2) < 0.01 True
在区间 \([0, 5]\) 中搜索目标值 \(71\) 没有找到解决方案:
>>> binary_search(lambda x: x**2 + 3*x + 1, 71, 0, 5) is None True
- Parameters:
function (Callable[[int | float], int | float])
目标 (整数 | 浮点数)
lower_bound (int | float)
upper_bound (int | float)
容差 (整数 | 浮点数)
- Return type:
整数 | 浮点数 | 无
- choose(n, k)[来源]¶
二项式系数 n 选 k。
\(\binom{n}{k}\) 描述了从\(n\)个元素的集合中选择\(k\)个元素的可能选择数。
参考文献
- Parameters:
n (int)
k (整数)
- Return type:
整数
- clip(a, min_a, max_a)[来源]¶
将
a裁剪到区间 [min_a,max_a]。接受任何可比较的对象(即支持 <, > 的对象)。 如果
a在min_a和max_a之间,则返回a。 否则,返回min_a和max_a中最接近的一个。示例
>>> clip(15, 11, 20) 15 >>> clip('a', 'h', 'k') 'h'