Python实现牛顿插值法(差商表)


def func(x,y,X,infor=True):
    list2=[y[0]]       #  差商表的对角线的第一个元素始终是y0
    count=1
    while(True):
        if len(y)>1:
            list=[]                 # 空列表用来保存,每次计算后差商表的行
            for i in range(len(y)-1):
                n=x[i+count]-x[i]
                m=y[i+1]-y[i]
                l=m/n
                list.append(l)
            list2.append(list[0])        # list2用来记录差商表的对角线元素,每计算一次,取行的第一个元素
            count += 1
            y = list
        else:
            break
    if infor:                           # 判断是否要继续计算,结果
        W=0
        for i in range(len(list2)):
            if i==0:
                w=list2[i]
            else:
                w = list2[i]
                for j in range(i):
                    w*=(X-x[j])
            W+=w
        print('牛顿插值:', W)
    return '牛顿差商表对角线列:%s' %list2

ret=func([0.32, 0.34, 0.36],[0.314567, 0.333487, 0.352274],'',infor=False)
print(ret)
ret=func([0.32, 0.34, 0.36],[0.314567, 0.333487, 0.352274],0.3367)
print(ret)

运行结果:
Python实现牛顿插值法(差商表)

猜你喜欢

转载自blog.51cto.com/13747953/2308551