二分法
应用二分法求解方程在区间内的数值解,要求绝对误差小于。
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x3 - x - 1
def HALF(a,b,epsilon):
k = 1 + int((np.log(b-a) - np.log(2epsilon)) / (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)