python 计算牛顿差商,计算并化简牛顿插值多项式

1. 程序

1.1 导入库

import numpy as np
import sympy as sy

1.2 函数

def NewtonInt(x_value, y_value):
    """
    计算牛顿插值差商表
    :param x_value: x序列
    :param y_value: y序列
    :return: 差商表矩阵, 字符串插值多项式
    """
    N=len(x_value)
    res= np.zeros((N, N))
    res[:, 0]= y_value
    for i in range(1,N):    # i 阶
        for j in range(N-i):  # j 个
            res[j, i]= (res[j+1, i-1]- res[j, i-1])/(x_value[i + j] - x_value[j])
            # print("y1=%f; y2=%f; x1=%f; x2=%f; res=%f; "%(res[j+1, i-1], res[j, i-1],x[i+j], x[j], res[j,i]))

    print("\n 差商表:\n   {:^16}{:^16}".format("xi","yi"), end="")
    for i in range(1,N):
        print("{:^14}".format("{:2d}阶差商".format(i)), end="")
    print("")
    for i in range(N):    # i 阶
        print("%16.4E" % (x_value[i]), end="")
        for j in range(i+1):  # j 个
            print("%16.4E"%res[i-j, j], end="")
        print("")

    # str_Nx= "\n\nN(x)= "
    str_Nx=""
    for i in range(N):  # i 阶
        str_Nx+= "%f"%res[0 , i]
        for j in range(i):  # j 个
            str_Nx +="*(x- %f)" % x_value[j]
        str_Nx+= " + "
    print("\n\n原始多项式:\n"+ str_Nx[0:-3])
    print("\n\n化简的多项式:")
    print(sy.simplify(str_Nx[0:-3]))
    return res, str_Nx[0:-3]

2.测试

2.1 测试程序

x_v=np.array([0.4, 0.55, 0.65, 0.8, 0.9, 1.05])
y_v=np.array([0.41075, 0.57815, 0.69675, 0.88811, 1.02652, 1.25382])
# x_v=np.array([0,1,2,5,3])
# y_v=np.array([2,3,12,147,30])
res, Nx= NewtonInt(x_v,y_v)

2.2 输出结果

差商表:
          xi              yi            1阶差商          2阶差商          3阶差商          4阶差商          5阶差商     
      4.0000E-01      4.1075E-01
      5.5000E-01      5.7815E-01      1.1160E+00
      6.5000E-01      6.9675E-01      1.1860E+00      2.8000E-01
      8.0000E-01      8.8811E-01      1.2757E+00      3.5893E-01      1.9733E-01
      9.0000E-01      1.0265E+00      1.3841E+00      4.3347E-01      2.1295E-01      3.1238E-02
      1.0500E+00      1.2538E+00      1.5153E+00      5.2493E-01      2.2867E-01      3.1429E-02      2.9304E-04


原始多项式:
0.410750 + 1.116000*(x- 0.400000) + 0.280000*(x- 0.400000)*(x- 0.550000) + 0.197333*(x- 0.400000)*(x- 0.550000)*(x- 0.650000) + 0.031238*(x- 0.400000)*(x- 0.550000)*(x- 0.650000)*(x- 0.800000) + 0.000293*(x- 0.400000)*(x- 0.550000)*(x- 0.650000)*(x- 0.800000)*(x- 0.900000)


化简的多项式:
0.000293*x**5 + 0.0302711*x**4 + 0.1236151075*x**3 + 0.02961707125*x**2 + 0.9901178008*x + 0.00127484091999994

与书本结果对比:

 

 

你可能感兴趣的:(python,算法,牛顿插值,python)