【发布时间】:2021-12-07 13:29:39
【问题描述】:
对于 Newton-Raphson 方法,我被要求编写一个循环来调用该函数,直到它收敛,以便 x(n) 和 x(n+1) 的值相差小于一个小数 e =10^-8,但是,我不太清楚如何创建这个循环。
这是我目前的代码
def newton_step(f, fp, x0):
return x0-(f(x0)/fp(x0))
import numpy as np
def f(x):
return x**3 + x**2 +2
def fp(x):
return 3*x**2 + 2*x
x = newton_step(f, fp, (x0))
count = 0 #to count the number of iterations required to satisfy the condition
while (x0 - x) <= 10**-8:
x0 = newton_step(f, fp, (x0))
count += 1
print(x0, x)
【问题讨论】:
-
您遇到的具体问题是什么?
-
我收到“NameError: name 'x0' is not defined”
-
您正在使用一个函数来使 2 个值彼此接近,对吗?您必须提供这 2 个起始值 (x, x0)
-
非常感谢!
标签: python python-3.x loops newtons-method