Python牛顿迭代法的应用

老师布置个小问题,我就写了一写

运行结果和代码都放出来了

 在main函数里fun修改要求零点的函数,记得他的导数dfun也要修改一下哦

在newton函数里可以修改time和threshold来调整精度哈

还有,这个程序要输入求解的范围,在findstartpoint函数里修改choose部分哦

import matplotlib.pyplot as plt
import numpy as np
from sympy import *

def newton(x0,time,threshold,f,df):
    while time>0:
        x1 = x0 - f(x0) / df(x0) 
        if abs(f(x1)) < threshold:
            return x1
        x0 = x1
        time -= 1

def find_start_point(f):
    choose = np.linspace(0, 60, 100, endpoint=True)
    start = [i  for i in choose if f(i) < 0.01]
    return start

def visualization_and_error_analysis(lists,f):
    fig = plt.figure()
    ax1=fig.add_subplot(3,1,1)
    plt.plot([i for i in range(60)],[f(i) for i in range(60)],label="the true curve")
    plt.scatter([i for i in lists],[f(i) for i in lists],label="result from newton",s=2,c="red")
    plt.title("the result of Newton’s iterative method")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    ax2 = fig.add_subplot(3,1,3)
    plt.bar([i for i in range(1,1+len(lists))],[f(i) for i in lists],label="error")
    print("误差如下")
    print([f(i) for i in lists])
    plt.title("the error of Newton’s iterative method")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.show()

def main():
    fun = lambda x:exp(-x)-sin(x)
    dfun = lambda x:-exp(-x)-cos(x)
    start = find_start_point(fun)
    result,result1 = [],[]
    for i in start:
        try:
            result.append(newton(i,1000,1e-10,fun,dfun))
        except:
            continue
    result = sorted(result)
    result1 = list(set([round(i,7) for i in result]))
    result1 = sorted(result1)
    print("这是保留了7位小数后的输出")
    print(result1)
    print("下面展示的是由牛顿迭代法找出的所有零点和误差分析")
    visualization_and_error_analysis(result,fun)


if __name__ == "__main__":
    main()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

River Chandler

谢谢,我会更努力学习工作的!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值