这只是为了提供一个适用于所示示例的“自定义”平分方法。然而,我仍然建议使用公认的答案。
def bisect(func, x_min, x_max, x_func=None,
tol=None, iter_max=None, **kwargs):
y_min = func(x_min, **kwargs)
if y_min > 0:
msg = "Warning: no solution as y_min>0, with x_min=%f."
print(msg % x_min)
return x_min
y_max = func(x_max, **kwargs)
if y_max <= 0:
msg = "Warning: no solution as y_max<=0, with x_max=%f."
print(msg % x_max)
return x_max
if tol is None and iter_max is None:
tol = 1e-7
if x_func is None:
x_func = lambda x0, x1: (x1+x0)/2
from itertools import count, islice
x_last = np.infty
for cnt in islice(count(), iter_max):
x_new = x_func(x_min, x_max)
y_new = func(x_new, **kwargs)
if y_new<=0:
x_min = x_new
else:
x_max = x_new
if (tol is not None) and abs(x_last - x_new) < tol:
break
x_last = x_new
return x_min if y_new>0 else x_max
def func(x):
return max(x**2 - 2, 0) if x > 0 else 0
ret = bisect(func, x_min=-6, x_max=8)
print(ret)
有趣的是
bisect()
看起来比
root_scalar
这个基本函数类型的方法
func(x)
。但我预计这种优势会在更复杂的函数中消失。
%timeit bisect(func, x_min=-6, x_max=8, iter_max=None, tol=1e-7)
# 46.3 µs ± 1.96 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit root_scalar(wrapper(func), bracket=[-6, 8], xtol=1e-7)
# 84.6 µs ± 6.29 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
# Test that the results are equivalent:
x1 = bisect(func, x_min=-6, x_max=8, iter_max=None, tol=1e-7)
x2 = root_scalar(wrapper(func), bracket=[-6, 8], xtol=1e-7).root
assert abs(x2-x1) < 1e-7
# 2.9078300656237843e-08