Untitled
unknown
plain_text
4 years ago
948 B
4
Indexable
def fprime(x):
h=10**-7
return (f2(x+h)- f2(x))/h
def newton(f, x0, eps=10**-4, max_iter=100):
x1 = x0-1
x=[]
y=[]
u=[]
for i in np.arange(2,fprime(x0+1),eps):
x.append(i)
y.append(f2(i))
plt.plot(x,y)
while max_iter>0 and (abs(x1-x0)) > eps and (abs(f2(x0)))>eps:
plt.plot([x0], [f2(x0)], color="red")
plt.scatter(x0, f2(x0), c="red")
# plt.plot([x0-0.1, x0+0.1], [f2(x0)-eps, f2(x0)+eps])
plt.plot([x0-0.5,x0+0.5],[f2(x0)-fprime(x0),f2(x0)+eps], linestyle="--", color="red")
# plt.plot([1,5],[5,8])
x1 = x0
x0 = x0 - f2(x0)/fprime(x0)
# plt.axvline(x=x0, linestyle="--", color="red")
u.append(x0)
max_iter -= 1
print(x0)
plt.grid(linestyle="--")
c=x0
plt.title("C={}".format(c))
plt.xlabel("x")
plt.ylabel("y")
plt.show()
newton(f2, 4)
Editor is loading...