欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

牛顿插值多项式(python实现)

程序员文章站 2022-03-17 08:49:25
...

理论知识

牛顿插值多项式(理论知识)

目标函数

f(x)=11+x2

插值点为[-10, 10]上的整数点。

图片

牛顿插值多项式(python实现)

代码实现

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


def f(X):
    return 1 / (X ** 2 + 1)


def ff(X=list()):
    if len(X) < 2:
        raise ValueError('X\'s length must be bigger than 2')
    ans = 0
    for i in range(len(X)):
        temp = 1.0
        for j in range(len(X)):
            if j == i:
                continue
            temp *= (X[i] - X[j])
        ans += (f(X[i]) / temp)
    return ans


def draw():
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    X = np.linspace(-10, 10, 100)

    TargetY = f(X)
    GetY = [Px.subs(x, i) for i in X]

    plt.plot(X, TargetY, label=r'$\frac{1}{x^2+1}$')
    plt.plot(X, GetY, label='$L(x)$')
    plt.legend()
    plt.show()


def generatePx(DataX):
    ans = f(DataX[0])
    if len(DataX) == 1:
        return ans
    else:
        temp = 1
        for i in range(len(DataX) - 1):
            temp *= (x - DataX[i])
            ans += ff(DataX[:i + 2]) * temp
        return ans


if __name__ == '__main__':
    x = sympy.symbols('x')

    DataX = np.linspace(-10, 10, 11)  # 插值点

    Px = sympy.expand(generatePx(DataX))
    draw()