Python牛顿迭代法的应用

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

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

Python牛顿迭代法的应用_第1张图片

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

你可能感兴趣的:(#,科学计算案例,python)