分享

Python实现所有算法-正割法(Secant)

 云深无际 2022-07-12 发布于内蒙古

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

示意图

迭代的起点

推广的公式

核心code,直接放上去

眼熟不

你可以编写一个简单的函数来测试这个功能

就是这么简单,当然了字数这么少,还成为不了一篇原创文章。再写一个小程序。

我们可以使用Matploatlib的绘图功能模拟

引入

写好要计算的函数

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 = 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()

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多