数值分析正割法python3实现并绘图

来源:互联网 发布:磁力在线播放 源码 编辑:程序博客网 时间:2024/06/05 19:13
import numpy as npimport matplotlib.pyplot as pltprint("题目:用正割法求x^3-x-1=0在x=1.5的一个根")print("---------------------------------------")i = 0def result(x):    y = (x**3-x-1)/(3*x**2-1)    return x-ydef 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 = 0plt.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()

正割法是近似的牛顿切线法,把求导用斜率代替。
用切线不断逼近函数的单根