def solve(func, x = 0.0, step = 1e3, prec = 1e-10):
"""Find a root of func(x) using the bisection method.
The function may be rising or falling, or a boolean expression, as long as
the end points have differing signs or boolean values.
Examples:
solve(lambda x: x**3 > 1000) to calculate the cubic root of 1000.
solve(math.sin, x=6, step=1) to solve sin(x)=0 with x=[6,7).
"""
test = lambda x: func(x) > 0 # Convert into bool function
begin, end = test(x), test(x + step)
assert begin is not end # func(x) and func(x+step) must be on opposite sides
while abs(step) > prec:
step *= 0.5
if test(x + step) is not end: x += step
return x
下面是一些显示基本技术的代码:
我的实现比其他解决方案更通用,也更简单:(和公共域)
您可以在前面使用scipy.optimize.bisect的堆栈溢出问题here中看到解决方案。或者,如果您的目的是学习,Wikipedia entry on the bisection method中的伪代码是在Python中进行自己实现的一个很好的指南,正如前面问题的注释者所建议的那样。
相关问题 更多 >
编程相关推荐