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

理论知识

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

目标函数
f ( x ) = 1 1 + x 2 f(x) = \frac{1}{1+x^2} f(x)=1+x21

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

图片

这里写图片描述

代码实现

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

牛顿插值多项式是一种用于插值的数值方法,它基于牛顿差商公式。牛顿插值多项式可以表示为以下形式: P(x) = f[x0] + f[x0, x1](x - x0) + f[x0, x1, x2](x - x0)(x - x1) + ... + f[x0, x1, ..., xn](x - x0)(x - x1)...(x - xn-1) 其中,f[x0]表示函数f在点x0处的函数值,f[x0, x1]表示f在区间[x0, x1]上的斜率,f[x0, x1, x2]表示f在区间[x0, x1, x2]上的曲率,以此类推。 在Python中,我们可以通过编写函数实现牛顿插值多项式。下面是一个示例代码: ```python def newton_interpolation(x, y): n = len(x) coefficients = [y[0]] for j in range(1, n): temp = 0 for i in range(j): product = 1 for k in range(i+1): product *= (x[j] - x[k]) temp += (y[j] - coefficients[i]) / product coefficients.append(temp) def polynomial(t): result = coefficients[0] for i in range(1, n): product = 1 for j in range(i): product *= (t - x[j]) result += coefficients[i] * product return result return polynomial ``` 使用上述代码,我们可以通过给定的数据点集合(x, y)来生成一个牛顿插值多项式。例如,假设我们有以下数据点: x = [1, 2, 3, 4] y = [2, 3, 5, 10] 我们可以使用上述代码生成牛顿插值多项式,并将其赋值给一个变量: ```python polynomial = newton_interpolation(x, y) ``` 然后,我们可以使用生成的多项式计算任意点的插值值。例如,我们可以计算x=2.5时的插值值: ```python interpolated_value = polynomial(2.5) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gc.collect()

公众号“肥宅Sean”欢迎关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值