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

(三) 弦截法(试位法)求根

时间:2017-12-11 11:30:31      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:input   on()   idt   label   bsp   style   show   atp   连线   

 

 1 # -*- coding: utf-8 -*-
 2 #coding=utf-8
 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, 2, -10, 50])
13 #开启交互
14 plt.ion()
15 #设置xy轴的名称
16 plt.xlabel("X")
17 plt.ylabel("Y")
18 x = np.linspace(0, 10, 100)
19 y = x**3+4*x**2-10
20 plt.plot(x, y, label="$x**3+4*x**2-10$", color="red", linewidth=1)
21 plt.show()
22 #获取零点俩边的x值
23 x1 = float(input("请输入零点左边x1的值:x1 = "))
24 x2 = float(input("请输入另一边x2的值:x2 = "))
25 
26 while(1):
27    #每运行一次输出俩边的值
28     print x1,x2
29 
30    # 函数式
31     x=Symbol("x")
32     f = x**3+4*x**2-10
33 
34     #两边的y值为
35     y1 = x1**3 + 4*x1**2 - 10
36     y2 = x2**3 + 4*x2**2 - 10
37     print y1,y2
38 
39    #两点连线与x轴交点的x值
40     x = x.subs(x,x2-(y2*(x1-x2)/(y1-y2)))
41     #print x
42     #刚好是函数零点时
43     if f==0:
44         break
45 
46     #交于y=0时
47     if x==0.0:
48          if x2>x:
49             x1 = x
50             y1 = x1 ** 3 + 4 * x1 ** 2 - 10
51          elif x2<x:
52             x2 = x
53             y2 = x2 ** 3 + 4 * x2 ** 2 - 10
54 
55      #纵坐标乘积为负且不满足终止条件时继续循环
56     elif y1*y2<0:
57         x1=x
58         y1 = x1 ** 3 + 4 * x1 ** 2 - 10
59     #取终止值为 0.01  满足条件
60     if  (x**3+4*x**2-10)>-0.01 and  (x**3+4*x**2-10)<0.01 :
61         break
62 
63     plt.plot([x1, x2], [x1**3+4*x1**2-10, x2**3+4*x2**2-10])
64     plt.pause(0.05)
65 show_res = [x= + str(x) +  ]
66 plt.text(1, 5, show_res)
67 print "估计结果为:x = "
68 print x
69 while True:
70     plt.pause(0.05)

 

(三) 弦截法(试位法)求根

标签:input   on()   idt   label   bsp   style   show   atp   连线   

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

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