Reputation: 75
epsilon is set to 0.1 but it gives me results until 1.2. I dont know what causes that. Can anyone help?
def evaluate_poly(poly, x):
total = 0.0
for i in range(len(poly)):
total += poly[i] * (x ** i)
return total
def compute_deriv(poly):
deriv = []
if len(poly) < 2:
return [0.0]
else:
for i in range(1, len(poly)):
deriv.append(float(poly[i] * i))
return deriv
def compute_root(poly, x_0, epsilon):
num = 0
root = x_0
while abs(evaluate_poly(poly, root)) >= epsilon:
root = root - evaluate_poly(poly, root) / evaluate_poly(compute_deriv(poly), root)
num += 1
return [root, num]
print(compute_root((1.0,-2.0,1.0), 14, 0.1))
Upvotes: 1
Views: 122
Reputation: 149155
You are trying to solve numerically x2 - 2 * x + 1 = 0. We know that the equation has a double root at x=1. But at that point (x=1), the derivative (2 * x - 2) is 0. That mean that the error in y will always be one magnitude order below the error in x, so the result of x = 1.2, y ~ 0.04 < 0.1 is not at all a surprise.
The difference xn - xn-1 would be a much better guess of the error in x:
def compute_root1(poly, x_0, epsilon):
num = 0
root = x_0
while True:
root1 = root - evaluate_poly(poly, root) / evaluate_poly(compute_deriv(poly), root)
if abs(root1 - root) < epsilon: break
num += 1
root = root1
return [root1, num+1]
It gives:
>>> print(compute_root1((1.0,-2.0,1.0), 14, 0.1))
[1.05078125, 8]
Upvotes: 3
Reputation: 438
epsilon represents y error (evaluate poly if you will), but your result of 1.2... is x value, where y is 0. in this case your y is 0.0412 and is lower than 0.1 so code is ok.
change your return in compute_root to:
return [root, num, abs(evaluate_poly(poly, root))]
Upvotes: 2