1 #coding=utf-8 2 from sympy import * 3 import numpy as np 4 from sympy import * 5 import math 6 import matplotlib.pyplot as plt 7 8 plt.close() 9 fig = plt.figure() 10 #网格可见 11 plt.grid(True) 12 plt.axis([0, 5, -2, 25]) 13 #开启交互 14 plt.ion() 15 #plt.title("牛顿法") 16 #设置xy轴的名称 17 plt.xlabel("X") 18 plt.ylabel("Y") 19 x = np.linspace(0, 10, 100) 20 y = x**2-2 21 plt.plot(x, y, label="$y$", color="red", linewidth=1) 22 plt.show() 23 24 25 #定义变量x 26 x = Symbol(‘x‘) 27 #定义函数f 28 f = x**2-2 29 x0=5.0 30 while(1): 31 y0=x0**2-2 32 g = diff(f,x,1) 33 k = g.subs(x,x0) 34 # y1 = f.sub(x,x0) 35 b = y0-k*x0 36 x1=-b/k 37 plt.plot([x0,x0],[0,y0]) 38 plt.plot([x1,x0],[0,y0]) 39 print(x1) 40 if (abs(x1 - x0) < 0.00001): 41 x0=x1 42 break 43 x0=x1 44 plt.pause(0.5) 45 show_res = ‘[x=‘ + str(x0) + ‘]‘ 46 plt.text(1,1, show_res) 47 while True: 48 plt.pause(0.05)