Python 多项式的二分根

Python 多项式的二分根,python,bisection,Python,Bisection,我是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 coe

我是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二等分(a、b、多边形、公差):
多边形(a)=0
尝试:
如果
"""
假设多边形(a)=0。
:param a:poly(a)=0如果不为真,则引发异常
:param poly:多项式系数,低阶优先
:参数公差:大于0
:return:a和b之间的值,在多项式根的公差范围内
"""
如何使用二分法找到根?我已经被提供了一个测试脚本来测试这些

编辑:我遵循伪代码,最终得出以下结论:

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
def二等分(a、b、多边形、公差):
#多边形(a)=0
差值=绝对值(a-b)
xmid=(a-b)/2
n=1
nmax=60

而n除了
xmid
mid
的混乱之外,您的代码似乎还不错
mid=(a+b)/2
而不是
mid=(a-b)/2
,并且您不需要
差异
变量

把它弄干净一点:

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))
def符号(x):
如果x<0,则返回-1,否则返回(如果x>0,则返回1,否则返回0)
def二等分(a、b、多边形、公差):
mid=a将被覆盖
对于范围(60)内的i:
中期=(a+b)/2
如果多边形(mid)==0或(b-a)/2<公差:
中途返回
如果符号(poly(mid))==符号(poly(a)):
a=中等
其他:
b=中等
中途返回
打印(二等分(-10**10,10**10,λx:x**5-x**4-x**3-x**2-x+9271,0.00001))

只需遵循此处的伪代码:?为什么要重新发明轮子?