用matlab写三道数值分析拉格朗日插值题
时间: 2023-11-02 21:02:22 浏览: 51
好的,下面给您三个数值分析的拉格朗日插值题的 Matlab 代码实现。
1. 插值多项式
```matlab
% 提供的数据点
x = [0 1 2];
y = [1 2 4];
% 计算插值多项式
syms t;
n = length(x);
L = sym(zeros(n, 1));
for i = 1:n
L(i) = y(i);
for j = 1:n
if j ~= i
L(i) = L(i) * (t - x(j)) / (x(i) - x(j));
end
end
end
P = simplify(sum(L));
disp(['插值多项式为:' char(P)]);
```
2. 计算插值多项式在某一点处的函数值
```matlab
% 提供的数据点
x = [0 1 2];
y = [1 2 4];
% 计算插值多项式
syms t;
n = length(x);
L = sym(zeros(n, 1));
for i = 1:n
L(i) = y(i);
for j = 1:n
if j ~= i
L(i) = L(i) * (t - x(j)) / (x(i) - x(j));
end
end
end
P = simplify(sum(L));
% 计算插值多项式在 t=1.5 处的函数值
t = 1.5;
val = double(subs(P, t));
disp(['插值多项式在 t=1.5 处的函数值为:' num2str(val)]);
```
3. 绘制原函数和插值多项式的图像
```matlab
% 提供的数据点
x = [0 1 2];
y = [1 2 4];
% 计算插值多项式
syms t;
n = length(x);
L = sym(zeros(n, 1));
for i = 1:n
L(i) = y(i);
for j = 1:n
if j ~= i
L(i) = L(i) * (t - x(j)) / (x(i) - x(j));
end
end
end
P = simplify(sum(L));
% 绘制原函数和插值多项式的图像
f = @(t) exp(t); % 原函数
t = linspace(0, 2, 1000);
y_f = f(t);
y_P = double(subs(P, t));
plot(t, y_f, 'r-', t, y_P, 'b--');
legend('原函数', '插值多项式');
```