求根 - 牛顿迭代¶
$$ x_{k+1} = x_k - \frac{f(x_k)}{f^{'}(x_k)} $$
$$\sqrt{2} = 1.4142135623730951$$
In [2]:
def newton_get_root(f, df, x0, n):
root = x0
for i in range(1, n + 1):
root = root - f(root) / df(root)
print(f'第{i}次迭代找到根为 {root}')
In [3]:
def f1(x):
return x * x - 2
def df1(x):
return 2 * x
newton_get_root(f=f1, df=df1, x0=1, n=10)
第1次迭代找到根为 1.5 第2次迭代找到根为 1.4166666666666667 第3次迭代找到根为 1.4142156862745099 第4次迭代找到根为 1.4142135623746899 第5次迭代找到根为 1.4142135623730951 第6次迭代找到根为 1.414213562373095 第7次迭代找到根为 1.4142135623730951 第8次迭代找到根为 1.414213562373095 第9次迭代找到根为 1.4142135623730951 第10次迭代找到根为 1.414213562373095
$$ln(2)=0.6931471805599453$$
In [4]:
import math
def f2(x):
return math.exp(x) - 2
def df2(x):
return math.exp(x)
newton_get_root(f=f2, df=df2, x0=1, n=10)
第1次迭代找到根为 0.7357588823428847 第2次迭代找到根为 0.6940422999189153 第3次迭代找到根为 0.6931475810597714 第4次迭代找到根为 0.6931471805600254 第5次迭代找到根为 0.6931471805599453 第6次迭代找到根为 0.6931471805599453 第7次迭代找到根为 0.6931471805599453 第8次迭代找到根为 0.6931471805599453 第9次迭代找到根为 0.6931471805599453 第10次迭代找到根为 0.6931471805599453
In [5]:
def newton_simple_get_root(f, df, x0, n):
root = x0
dfx0 = df(x0)
for i in range(1, n + 1):
root = root - f(root) / dfx0
print(f'第{i}次迭代找到根为 {root}')
In [6]:
def f1(x):
return x * x - 2
def df1(x):
return 2 * x
newton_simple_get_root(f=f1, df=df1, x0=1, n=10)
第1次迭代找到根为 1.5 第2次迭代找到根为 1.375 第3次迭代找到根为 1.4296875 第4次迭代找到根为 1.407684326171875 第5次迭代找到根为 1.4168967450968921 第6次迭代找到根为 1.4130985519638084 第7次迭代找到根为 1.4146747931827024 第8次迭代找到根为 1.4140224079494415 第9次迭代找到根为 1.4142927228578732 第10次迭代找到根为 1.4141807698935047