import numpy as np
import matplotlib.pyplot as plt
print("题目:用正割法求x^3-x-1=0在x=1.5的一个根")
print("---------------------------------------")
i = 0
def result(x):
y = (x**3-x-1)/(3*x**2-1)
return x-y
def Y(x):
global i
i = i+1
plt.plot([x, x], [0, (x**3-x-1)])
plt.plot([x, result(x)], [(x**3-x-1), 0])
temp = round(x-result(x),5)
if(temp== 0.0):
print('正割法第',i,'次')
print('解得:',round(x,5))
x = result(x)
y = (result(x)**3- result(x) - 1)
plt.plot(x, y, ".")
plt.plot(x,y,"g-")
plt.annotate("(1.32472,1.32472)", xy=(result(x), (result(x)**3- result(x) - 1)),
xytext=(result(x) - 0.5, (result(x)**3- result(x) - 1) +2), color='k', fontsize=10)
else:
Y(result(x))
Y(2.7)
x = 0
plt.title("secant method")
x = np.linspace(0,3)
plt.xlim(0,3)# 固定坐标
plt.ylim(-5,20)
plt.plot(x,x**3-x-1,"b-")
plt.grid(True)
plt.plot([0,3],[0,0],"--")
plt.show()
正割法是近似的牛顿切线法,把求导用斜率代替。
用切线不断逼近函数的单根