forked from Ligouhi/numerical-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewton_method.py
More file actions
85 lines (68 loc) · 1.36 KB
/
newton_method.py
File metadata and controls
85 lines (68 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 21:10:24 2018
@author: RenTeng
"""
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def loss(new,old):
rate = abs(new-old)/abs(new)
return rate
import sympy
def func(x):
fx = x**2-2*x
return fx
def func_deri(x):
x0 = sympy.Symbol("x")
a = sympy.diff(x0**2-2*x0,x0)
return a.evalf(subs = {x0:x})
#画函数图
xs = np.arange(-2,4,0.1)
y = []
for i in xs:
y.append(func(i))
fig = plt.figure(num=1)
plt.plot(xs,y)
plt.plot(xs,np.zeros(len(xs)))
plt.title("function plot")
plt.show()
x0 = float(input("input initialize x:"))
x1 = x0-func(x0)/func_deri(x0)
Range = x0
c = 0
x = []
y = []
x.append(x0)
y.append(func(x0))
x.append(x1)
y.append(0)
#迭代过程
while loss(x1,x0)>0.0001:
preloss = loss(x1,x0)
x0 = x1
x1 = x0-func(x0)/func_deri(x0)
x.append(x0)
y.append(func(x0))
x.append(x1)
y.append(0)
if(preloss<loss(x1,x0) and c>1):
print("Function does not converge!")
break
c+=1
#描点
xr = np.arange(-2,Range+1,0.1)
yr = []
plt.plot(xr,np.zeros(len(xr)))
for i in xr:
yr.append(func(i))
fig = plt.figure(num=1)
plt.plot(xr,yr)
plt.ion()
for i in range(0,len(x)-1):
plt.scatter(x[i],y[i])
plt.plot((x[i],x[i+1]),(y[i],y[i+1]))
# plt.pause(0.5)
plt.grid()
plt.show()
print("Approximate solution:",x1)