首先我们得知道一个定理:给定n+1个互异节点,则它的n次插值多项式是唯一存在的。
求解: L 1 ( x ) = a 1 x + a 0 L_1(x)=a_1x+a_0 L1(x)=a1x+a0
根据点斜式得到:
L 1 ( x ) = y 0 + ( y 1 − y 0 ) ( x 1 − x 0 ) ( x − x 0 ) L_1(x)=y_0+\frac{(y_1-y_0)}{(x_1-x_0)}(x-x_0) L1(x)=y0+(x1−x0)(y1−y0)(x−x0)
即:
L 1 ( x ) = ( x − x 1 ) ( x 0 − x 1 ) y 0 + ( x − x 0 ) ( x 1 − x 0 ) y 1 L_1(x)=\frac{(x-x1)}{(x_0-x_1)}y_0+\frac{(x-x0)}{(x_1-x_0)}y_1 L1(x)=(x0−x1)(x−x1)y0+(x1−x0)(x−x0)y1
这就是一次拉格朗日多项式
令
l 0 ( x ) = ( x − x 1 ) ( x 0 − x 1 ) l_0(x)=\frac{(x-x1)}{(x_0-x_1)} l0(x)=(x0−x1)(x−x1)
l 1 ( x ) = ( x − x 0 ) ( x 1 − x 0 ) l_1(x)=\frac{(x-x0)}{(x_1-x_0)} l1(x)=(x1−x0)(x−x0)
则一次拉格朗日多项式就可以表示为
l 1 ( x ) = y 0 l 0 ( x ) + y 1 l 1 ( x ) l_1(x)=y_0l_0(x)+y_1l_1(x) l1(x)=y0l0(x)+y1l1(x)
已知:
求解:
L 2 ( x ) = a 2 x 2 + a 1 x + a 0 L_2(x)=a_2x^2+a_1x+a_0 L2(x)=a2x2+a1x+a0
采用以下方法构造,令
L 2 ( x ) = A ( x − x 1 ) ( x − x 2 ) + B ( x − x 0 ) ( x − x 2 ) + C ( x − x 0 ) ( x − x 1 ) L_2(x)=A(x-x_1)(x-x_2)+B(x-x_0)(x-x_2)+C(x-x_0)(x-x_1) L2(x)=A(x−x1)(x−x2)+B(x−x0)(x−x2)+C(x−x0)(x−x1)
可以解出:
A = y 0 ( x 0 − x 1 ) ( x 0 − x 2 ) A=\frac{y_0}{(x_0-x_1)(x_0-x_2)} A=(x0−x1)(x0−x2)y0
B = y 1 ( x 1 − x 0 ) ( x 1 − x 2 ) B=\frac{y_1}{(x_1-x_0)(x_1-x_2)} B=(x1−x0)(x1−x2)y1
C = y 2 ( x 2 − x 0 ) ( x 2 − x 1 ) C=\frac{y_2}{(x_2-x_0)(x_2-x_1)} C=(x2−x0)(x2−x1)y2
于是可以得到:
L 2 ( x ) = ∑ i = 1 2 ( ∏ i = 0 , i ≠ j 2 x − x i x j − x i ) y j L_2(x)=\sum\limits_{i=1}^{2}(\prod\limits_{i=0,i\neq{j}}^{2}\frac{x-x_i}{x_j-x_i})y_j L2(x)=i=1∑2(i=0,i=j∏2xj−xix−xi)yj
该式称为二次拉格朗日多项式
如果令:
l 0 ( x ) = ( x − x 1 ) ( x − x 2 ) ( x 0 − x 1 ) ( x 0 − x 2 ) l_0(x)=\frac{(x-x1)(x-x_2)}{(x_0-x_1)(x_0-x_2)} l0(x)=(x0−x1)(x0−x2)(x−x1)(x−x2)
l 1 ( x ) = ( x − x 0 ) ( x − x 2 ) ( x 1 − x 0 ) ( x 1 − x 2 ) l_1(x)=\frac{(x-x0)(x-x_2)}{(x_1-x_0)(x_1-x_2)} l1(x)=(x1−x0)(x1−x2)(x−x0)(x−x2)
l 2 ( x ) = ( x − x 0 ) ( x − x 1 ) ( x 2 − x 0 ) ( x 2 − x 1 ) l_2(x)=\frac{(x-x0)(x-x_1)}{(x_2-x_0)(x_2-x_1)} l2(x)=(x2−x0)(x2−x1)(x−x0)(x−x1)
则
L 2 ( x ) = y 0 l 0 ( x ) + y 1 l 1 ( x ) + y 2 l 2 ( x ) L_2(x)=y_0l_0(x)+y_1l_1(x)+y_2l_2(x) L2(x)=y0l0(x)+y1l1(x)+y2l2(x)
由前面得规律可以得到n次拉格朗日插值多项式:
L 2 ( x ) = ∑ i = 1 n ( ∏ i = 0 , i ≠ j n x − x i x j − x i ) y j L_2(x)=\sum\limits_{i=1}^{n }(\prod\limits_{i=0,i\neq{j}}^{n}\frac{x-x_i}{x_j-x_i})y_j L2(x)=i=1∑n(i=0,i=j∏nxj−xix−xi)yj
import numpy as np
def LagrangeInterpolation(x):
grid_x = np.array([4, 5, 6])
k = len(grid_x)
value = np.array([10, 5.25, 1])
result = 0
for j in range(k):
result_l = 1
for i in range(k):
if i != j:
result_l = result_l * (x - grid_x[i]) / (grid_x[j] - grid_x[i])
result = result + value[j] * result_l
return result
if __name__ == '__main__':
x=18
result=LagrangeInterpolation(x)
print(result)
结果如下:
-11.0
参考:https://blog.csdn.net/u011699626/article/details/120394802