Scr*_*hon 7 python algorithm bisection python-3.x
我想制作一个Python程序,它将运行二分法来确定以下的根:
f(x) = -26 + 85x - 91x2 +44x3 -8x4 + x5
Run Code Online (Sandbox Code Playgroud)
二分法是用于估计多项式f(x)的根的数值方法.
我可以使用任何可用的伪代码,算法或库来告诉我答案吗?
这里有一些显示基本技术的代码:
>>> def samesign(a, b):
return a * b > 0
>>> def bisect(func, low, high):
'Find root of continuous function where f(low) and f(high) have opposite signs'
assert not samesign(func(low), func(high))
for i in range(54):
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint)):
low = midpoint
else:
high = midpoint
return midpoint
>>> def f(x):
return -26 + 85*x - 91*x**2 +44*x**3 -8*x**4 + x**5
>>> x = bisect(f, 0, 1)
>>> print x, f(x)
0.557025516287 3.74700270811e-16
Run Code Online (Sandbox Code Playgroud)
您可以在此处使用scipy.optimize.bisect的早期 Stack Overflow 问题中看到解决方案。或者,如果您的目的是学习,维基百科条目中关于二分法的伪代码是在 Python 中进行您自己的实现的一个很好的指南,正如前面问题的评论者所建议的那样。