I didn't already have a function to find roots of any polynomial, so I wrote one. It uses Newton's method. It's arguments are a list of coefficients, a lower bound and an upper bound on the range where to look for the zero.
It prints out: 2.5766641903207894
------
def findzero(poly,lo,hi):
""" poly is a list of coefficients of a polynomial and lo and hi are limits
on where to look for a zero of the function
e.g poly = [1,4,3,6] means x^3 + 4x^2 + 3x + 6
Use Newton-Raphson method """
revPoly = poly[::-1]
guess = lo
revDeriv = []
for i,v in enumerate(revPoly):
if i == 0:
continue
revDeriv.append(i*v)
def f(x):
ans = 0
for i,v in enumerate(revPoly):
ans += v*x**i
return ans
def fPrime(x):
ans = 0
for i,v in enumerate(revDeriv):
ans += v*x**i
return ans
finished = False
while not finished:
error = abs(f(guess)/fPrime(guess))
guess = guess - f(guess)/fPrime(guess)
if error < 10** -10:
finished = True
return guess
poly1 = [1,0,0,0,-1,-111]
print(findzero(poly1,2,3))
|
Posted by Larry
on 2023-02-25 08:24:58 |