The function compute_root uses Newton's method of successive approximation to find good enough approximations of the zeroes of polynomials (herein lies the problem). The function evalPoly computes the value of a polynomial at a particular x value, and the function ddx2 computes the derivative of a polynomial.
poly2 = (2,3,1,5) #poly2 represents the polynomial 5x^3+x^2+3x+1
def evalPoly(poly,x):
degree = 0
ans = 0
for index in poly:
ans += (index * (x**degree))
degree += 1
retu ans
retu degree
def ddx2(tpl):
lst = list(tpl)
for i in range(len(lst)):
lst[i] = lst[i]*i
if i != 0:
lst[i-1] = lst[i]
del lst[-1]
tpl = tuple(lst)
def compute_root(poly,x_0):
epsilon = .001
numGuesses = 1
if abs(evalPoly(poly,x_0)) <= epsilon:
ans = (evalPoly(poly,x_0),numGuesses)
print ans
retu ans
else:
x_1 = x_0 - (evalPoly(poly,x_0)/evalPoly(ddx2(poly),x_0))
# This is Newton's method of getting progressively better /
# "guesses"
compute_root(poly,x_1)
x_0 = x_1
numGuesses += 1
retu x_0
retu poly
compute_root(poly2,2) #Here I call the function *compute_root*
When I call the function I get this error:
Samuels-MacBook:python baicle$ python problemset2.py
Traceback (most recent call last):
File "problemset2.py", line 160, in <module>
compute_root(poly2,x_0)
File "problemset2.py", line 156, in compute_root
x_1 = x_0 - (evalPoly(poly,x_0)/evalPoly(ddx2(poly),x_0))
File "problemset2.py", line 126, in evalPoly
for index in poly:
TypeError: 'NoneType' object is not iterable
I know python functions retu none by default. I think that the error is produced because the value none is being passed into the parameter poly in evalPoly. Why is this happening?
I felt it would be prudent to include everything, even the function ddx2 (which hasn't been called yet in this example) because I don't know if you need it. I know compute_root needs a lot of work, this is just the first step. Thanks!!!
