我正在用python编写牛顿拉夫森规则代码,并且出现一个错误,我不知道为什么会发生。请帮助我。
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 - 10
def df(x):
return 2*x
def newton_raphson(x0, f, df, tol=1e-10, max_iter = 100):
x = x0
iteration = 0
x_values = x
while np.abs(f(x)) > tol and iteration < max_iter:
x = x - f(x) / df(x)
x_values.append(x)
iteration +=1
return x_values
x_values = np.linspace(-5, 5, 100)
plt.plot(x_values, f(x_values), label = 'f(x) = $x**2 - 10')
roots = newton_raphson(4.0, f, df)
plt.scatter(roots, [0]*len(roots), color='gray', label= 'roots')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Newton-Raphson Method')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.grid(color = 'gray', linestyle = '--', linewidth = 0.5)
plt.legend()
plt.show
这是代码,我正在尝试找到 x**2 - 10 的根
但是,出现错误,即“AttributeError:‘float’对象没有属性‘append’”。为什么会出现这个问题,我该如何解决这个问题?
在函数
newton_raphson()
中,将 x
定义为值 x0
的副本,然后将 x_values
定义为 x
的副本。因此 x_values
是您尝试向其附加值的单个浮点数。我认为 x_values
应该是一个空数组:
def newton_raphson(x0, f, df, tol=1e-10, max_iter = 100):
x = x0
iteration = 0
x_values = []
while np.abs(f(x)) > tol and iteration < max_iter:
x = x - f(x) / df(x)
x_values.append(x)
iteration +=1
return x_values
使用这个,你的代码可以正常工作。