1 # -*- coding: utf-8 -*- 2 #coding=utf-8 3 import numpy as np 4 import matplotlib.pyplot as plt 5 6 7 8 plt.close() 9 fig = plt.figure() 10 plt.grid(True) 11 plt.axis([0,2, -2, 5]) 12 plt.ion() 13 plt.xlabel("X") 14 plt.ylabel("Y") 15 x = np.linspace(0, 10, 100) 16 y = x**3-3*x+1 17 def f(x): 18 return y 19 20 plt.plot(x, y, label="$y$", color="red", linewidth=1) 21 plt.show() 22 a = input("请输入左边的值:a = ") 23 b = input("请输入右边的值:b = ") 24 c = input("请输入精度值:c = ") 25 26 #在一定精度之外循环 27 while(abs(a-b)>c): 28 # plt.cla() 29 #显示两边值分别为a,b 30 print a,b 31 x = (a+b)/2.0 32 f = a**3 - 3*a + 1 33 f1 = x**3-3*x+1 34 35 #如果x值直接得到结果跳出循环 36 if f1==0: 37 print x 38 break 39 40 #判断中间值在哪边 41 elif f * f1<0: 42 b = x 43 else: 44 a = x 45 plt.plot([a, b], [a ** 3 - 3 * a + 1, b ** 3 - 3 * b + 1]) 46 plt.pause(0.05) 47 show_res = ‘[x=‘ + str(x) + ‘]‘ 48 # plt.annotate(show_res,xytext=0.0,xy=x) 49 plt.text(0,0,show_res) 50 print "最终估计解为:x =",x 51 52 while True: 53 plt.pause(0.05)