python實現計算方法(一)--二分法求數值解

## 由於筆者學習《計算方法》,課程要求代碼實現。本文采用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))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章