Python数值分析--------牛顿插值法

先上代码:

import matplotlib.pyplot as plt
from math import *
allx = [i for i in range(2,11)]
ally = [i**3+5*i**2+6*i+7 for i in range(2,11)]
orders = 3

def newton_1(allx,ally,orders):
    difference_quotient = [[] for i in range(orders)]
    for j in range(1,1+orders):
        if j == 1:
            for i in range(orders+1-j):
                difference_quotient[j-1].append((ally[i]-ally[i+1])/(allx[i]-allx[i+1]))

        else:
            for i in range(orders+1-j):
                difference_quotient[j-1].append((difference_quotient[j-2][i]-difference_quotient[j-2][i+1]) / (allx[i] - allx[i+j]))

    t = []
    for i in difference_quotient:
        t.append(i[0])    

    sumx = [allx[0]-5+i*0.001 for i in range(1000*(allx[-1]-allx[0]+10))]
    sumy = []

    for j in sumx:
        r,v,f = 1,[],ally[0]
        for i in range(len(t)):
             r *= j - allx[i]
             v.append(r)
             f += difference_quotient[i][0] * v[i]
        sumy.append(f)

    plt.plot(sumx,sumy,c="yellow")
    allx = [i for i in range(-5,14)]
    ally = [i**3+5*i**2+6*i+7 for i in range(-5,14)]
    plt.scatter(allx,ally,s=2,c="red")
    plt.title("order = "+str(orders))
    plt.show()
    return sumx,sumy

p,q = newton_1(allx,ally,orders)

效果图

对于一个多项式函数,orders大于他的最高项似乎就Ok哈拉少了

Python数值分析--------牛顿插值法_第1张图片

 然而,并不是所有函数都是多项式形式的

这样就会有一个拟合过度或者拟合不足(数据组数量小于orders)的问题

拟合不足就如下面一组图:

这里先不列出拟合过度了,可以自己试试

Python数值分析--------牛顿插值法_第2张图片

 Python数值分析--------牛顿插值法_第3张图片

 Python数值分析--------牛顿插值法_第4张图片

 

你可能感兴趣的:(数值分析,python)