拉格朗日插值法
程序员文章站
2022-03-13 13:04:48
...
python代码实现插值拟合 1/(1+25x^2)
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return 1/(1+x**2)
def L(x, X, Y1):
Ln = 0.0000
t = 0
for j in X:
Molecule = 1.0000
Denominator = 1.0000
for i in X:
if i != j:
Molecule *= x-i
Denominator *= j-i
k = Molecule/Denominator
Ln += Y1[t] * k
t+=1
return Ln
X = np.arange(-5,5,0.5)
X1 = np.arange(-5,5,0.1)
Y = f(X)
Y1 = f(X1)
Y2 = L(X1, X, Y)
print(Y1)
print(Y2)
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax.set_ylim(-5,5)
ax.set_xlim(-5,5)
ax.plot(X1, Y1)
ax.plot(X1, Y2)
plt.show()
图结果
两边的差距过大的现象成为龙格现象。解决方案是分段插值