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

 

 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)

 

转载于:https://www.cnblogs.com/the-wang/p/8021491.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值