python实现计算方法(一)--二分法求数值解
## 由于笔者学习《计算方法》,课程要求代码实现。本文采用python实现二分法的数值求解,采用jupyter notebook。```python#采用Jupyter notebook,matplotlib内嵌,其他编辑器稍作修改即可import numpy as npimport matplotlib.pyplot as plt%matplotlib inline```py...
·
## 由于笔者学习《计算方法》,课程要求代码实现。本文采用python实现二分法的数值求解,采用jupyter notebook。
#采用Jupyter notebook,matplotlib内嵌,其他编辑器稍作修改即可
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#画出函数图像,这里采用的函数是x**5-3*x**2-2
x = np.linspace(1.5, 3, 1000)
y = x**5-3*x**2-2
plt.figure(figsize=(8,4))
plt.plot(x,y,color="blue",linewidth=2)
plt.xlabel("x")
plt.ylabel("y")
def solve_function(x):
#返回fx
return x**5-3*x**2-2
def dichotomy(left, right,eps):
#二分迭代
middle = (left+right)/2
count=0 # 统计迭代次数
while abs(solve_function(middle))>eps:
middle = (left+right)/2
if solve_function(left)*solve_function(middle)<=0:
right=middle
else:
left=middle
count=count+1
return count,middle
def nums():
#输入边界
left=float(input('please input left:'))
right=float(input('please input right:'))
eps=float(input('please input eps:'))
return left,right,eps
print('''left is 区间[a,b]中的a
right is 区间[a,b]中的b
eps is精度''')
while True:
#要求格式正确
try:
left,right,eps = nums()
if solve_function(left)*solve_function(right)==0:
if solve_function(left)==0:
print("根是{}".format(left))
continue
else:
print('根是{}'.format(right))
continue
elif solve_function(left)*solve_function(right)>0:
ex = print('left--right没有根,请重新输入')
raise ex
break
except:
print("input error,please input again")
count,middle=dichotomy(left, right,eps)
print("迭代%d次得到的根是%f" %(count,middle))
更多推荐
已为社区贡献1条内容
所有评论(0)