我是python的新手,我很难通过使用二分法来找到多项式的根。到目前为止,我有两种方法。一个用于评估值x
的多项式 def eval(x, poly):
"""
Evaluate the polynomial at the value x.
poly is a list of coefficients from lowest to highest.
:param x: Argument at which to evaluate
:param poly: The polynomial coefficients, lowest order to highest
:return: The result of evaluating the polynomial at x
"""
result = poly[0]
for i in range(1, len(poly)):
result = result + poly[i] * x**i
return result
下一个方法应该使用二分法来找到给定的多项式的根
def bisection(a, b, poly, tolerance):
poly(a) <= 0
poly(b) >= 0
try:
if
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
:param a: poly(a) <= 0 Raises an exception if not true
:param b: poly(b) >= 0 Raises an exception if not true
:param poly: polynomial coefficients, low order first
:param tolerance: greater than 0
:return: a value between a and b that is within tolerance of a root of the polynomial
"""
如何使用二分法找到根?我已经提供了一个测试脚本来测试这些。
编辑:我按照伪代码结束了这个:def bisection(a, b, poly, tolerance):
#poly(a) <= 0
#poly(b) >= 0
difference = abs(a-b)
xmid = (a-b)/2
n = 1
nmax = 60
while n <= nmax:
mid = (a-b) / 2
if poly(mid) == 0 or (b - a)/2 < tolerance:
print(mid)
n = n + 1
if sign(poly(mid)) == sign(poly(a)):
a = mid
else:
b = mid
return xmid
这是对的吗?由于返回xmid语句的缩进错误,我无法测试它。
答案 0 :(得分:0)
除了xmid
和mid
之外,您的代码似乎还可以。 mid = (a + b) / 2
代替mid = (a - b) / 2
,而您不需要difference
变量。
稍微清理了一下:
def sign(x):
return -1 if x < 0 else (1 if x > 0 else 0)
def bisection(a, b, poly, tolerance):
mid = a # will be overwritten
for i in range(60):
mid = (a+b) / 2
if poly(mid) == 0 or (b - a)/2 < tolerance:
return mid
if sign(poly(mid)) == sign(poly(a)):
a = mid
else:
b = mid
return mid
print(bisection(-10**10, 10**10, lambda x: x**5 - x**4 - x**3 - x**2 - x + 9271, 0.00001))