牛顿插值多项式(python实现)
生活随笔
收集整理的這篇文章主要介紹了
牛顿插值多项式(python实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
理論知識
牛頓插值多項式(理論知識)
目標函數
插值點為[-10, 10]上的整數點。
圖片
代碼實現
import sympy import numpy as np from matplotlib import pyplot as pltdef 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 = 0for i in range(len(X)):temp = 1.0for j in range(len(X)):if j == i:continuetemp *= (X[i] - X[j])ans += (f(X[i]) / temp)return ansdef draw():plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = FalseX = 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 anselse:temp = 1for i in range(len(DataX) - 1):temp *= (x - DataX[i])ans += ff(DataX[:i + 2]) * tempreturn ansif __name__ == '__main__':x = sympy.symbols('x')DataX = np.linspace(-10, 10, 11) # 插值點Px = sympy.expand(generatePx(DataX))draw()總結
以上是生活随笔為你收集整理的牛顿插值多项式(python实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛顿插值多项式
- 下一篇: 差分形式的牛顿插值公式(理论)