Reputation: 3
I'm making a newton-raphson rule code with python, and there is a error which I don't know why it's occuring. Please help me.
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
This is the code and I'm trying to find a roots of x**2 - 10
however, the error, which is saying 'AttributeError: 'float' object has no attribute 'append'' is occuring. Why is this problem taking place, and how can I solve this problem?
Upvotes: 0
Views: 52
Reputation: 807
In your function newton_raphson()
you define x
as a copy of the value x0
and then define x_values
as a copy of x
. So x_values
is a single float (= floating point number) to which you try to append values. This is not possible in Python. I assume x_values
is meant to be an empty list:
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
Using this, your code works fine.
If you want x_values to contain the value x0
you must still define it as list with that value in it:
x_values = [x0]
Upvotes: 0