非線性方程解法

1、二分法app

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x**3 - x - 1
def HALF(a,b,epsilon):#區間上下界和偏差限制
    k = 1 + int((np.log(b-a) - np.log(2*epsilon)) / (np.log(2)))
    ans = (a+b)/2
    height = []
    length = []
    for i in range(1, k+1):
        if f(ans) == 0 :
            break
        elif f(a)*f(ans) < 0 :
            b = ans
        else:
            a = ans
        height.append(ans)
        length.append(i)
        ans = (a+b)/2
        k += 1
    plt.plot(length, height)
    print(ans)

HALF(1, 1.5, 0.00000001)

二分法結果.png

相關文章
相關標籤/搜索