epsilon 设置为 0.1,但它给我的结果直到 1.2。我不知道是什么原因造成的。谁能帮忙?
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))
请您参考如下方法:
你正在尝试用数值求解 x2 - 2 * x + 1 = 0。我们知道方程在 x=1 处有一个双根。但在那一点 (x=1),导数 (2 * x - 2) 为 0。这意味着 y 中的误差将始终比 x 中的误差低一个数量级,因此 x = 1.2 的结果,y ~ 0.04 < 0.1 不足为奇。
xn - xn-1 的差值可以更好地猜测 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]
它给出:
>>> print(compute_root1((1.0,-2.0,1.0), 14, 0.1))
[1.05078125, 8]
