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 x=Symbol('x') 25 f = x**2 -2 26 x0 = 5.0 27 x1 = 4.0 28 while(1): 29 y0=f.subs(x,x0) 30 y1=f.subs(x,x1) 31 k=(y0-y1)/(x0-x1) 32 b=y0-k*x0 33 x2=-b/k 34 plt.plot([x1,x0],[0,y0]) 35 print(x2) 36 if(abs(x2-x1)<0.0001): 37 break 38 x0=x1 39 x1=x2 40 plt.pause(0.5) 41 show_res = '[x=' + str(x0) + ']' 42 plt.text(1,1, show_res) 43 while True: 44 plt.pause(0.05)