码迷,mamicode.com
首页 > 其他好文 > 详细

(四) 二分法求根

时间:2017-12-11 11:19:24      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:space   div   pre   pos   ann   ota   use   odi   line   

 

 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)

 

(四) 二分法求根

标签:space   div   pre   pos   ann   ota   use   odi   line   

原文地址:http://www.cnblogs.com/the-wang/p/8021496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!