Lagrange interpolation method experiment: find the Lagrange interpolation polynomial and the corresponding approximate value of x matlab implementation (code included)

1. Experimental requirements

Known function table:
Insert image description here
Find the Lagrange interpolation polynomial and calculate the approximate value of y at x=1.2.

2. MATLAB code

Solve for polynomials:

X = input('请输入横坐标向量X:\nX=');  % 获取用户输入的横坐标向量
Y = input('请输入纵坐标向量Y:\nY=');  % 获取用户输入的纵坐标向量
m = length(X);  % 获取节点个数
L = ones(m, m);  % 初始化基函数系数矩阵
for k = 1 : m  % 循环计算每个基函数的系数
    V = 1;  % 初始化基函数的临时变量
    for i = 1 : m
        if k ~= i  % 排除当前节点时的计算
            V = conv(V, poly(X(i))) / (X(k) - X(i));  % 在当前节点处计算基函数的系数
        end
    end
    L(k, :) = V;  % 将基函数的系数存储到矩阵中
end
l = sym(zeros(m, 1));  % 初始化基函数数组
for k = 1 : m  % 遍历基函数系数矩阵
    l(k) = poly2sym(L(k, :));  % 将基函数系数转化为符号表达式
end
fprintf('基函数为:\n');
for k = 1 : m  % 输出每个基函数的表达式
    fprintf('q%d(x)=%s\n', k, char(l(k)));
end
P = sym(0);  % 初始化拉格朗日多项式
for k = 1 : m  % 计算拉格朗日多项式的表达式
    P = P + Y(k) * l(k);
end
fprintf('拉格朗日多项式为:\nP(x)=%s\n', char(P));  % 输出拉格朗日多项式的表达式

Solving for an approximation:

% 定义拉格朗日插值多项式的系数
coeff = [1/12, -29/6, 1/12, 62/3];

% 计算 x=1.2 处的 y 的近似值
x = 1.2;
y_approx = polyval(coeff, x);

% 显示结果
disp(['当 x = ' num2str(x) ' 时,y 的近似值为 ' num2str(y_approx)]);

3. Experimental results

Please enter the abscissa vector
X : )/12 - (19 x)/6 - x^3/12 + 10/3 q2(x)=(29 x)/6 - (5 x^2)/3 + x^3/6 - 10/3 q3(x)=(4 x^2)/3 - (17 x)/6 - x^3/6 + 5/3 q4(x)=(7 x)/6 - (7 x^2)/12 + x^3/12 - 2/3 Lagrangian polynomial is: P(x)=x^2/12 - (29*x)/6 + x^3/12 + 62/3 when x = 1.2 , the approximate value of y is 13.9507









Insert image description here

Reference: lagrange interpolation method: matlab implementation of finding Lagrange interpolation polynomials (code and examples included)

Guess you like

Origin blog.csdn.net/m0_63007797/article/details/133531585