-1

我是 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

这个对吗?由于 return xmid 语句的缩进错误,我无法对其进行测试。

4

1 回答 1

0

你的代码看起来不错,除了xmidmid. 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))
于 2015-08-31T18:32:33.987 回答