拉格朗日插值多项式在MATLAB中的实现
Hi! 这是我的一个CSDN博客
例
以下给出了针对题(2)的使用方法
输入:
1.节点值
2.需要插值的原函数
对于题(2)需要设置参数为:
xx = [0,0.25,0.5,1];% The nodes(needs to be arranged in order)
y = cos(x)+sin(x); % The function needed to be interpolated
对于题(1)则设置参数为
xx = [0,0.3,0.6];% The nodes(needs to be arranged in order)
y = exp(2*x)*cos(3*x); % The function needed to be interpolated
输出:
1.拉格朗日插值多项式函数 L
2.截断误差限 R
如:
以下是该脚本函数针对题(2)在MATLAB中的输出
The Largrange interpolation polynominal is:
- 0.079318038853536971606466514918676*x^3 - 0.54550876234592496004170044075304*x^2 + 1.006600091875498155701605884745*x + 1.0The Bound of absolute error is:
0.058924941169576826316411910511306*abs(x*(x - 0.25)*(x - 0.5)*(x - 1.0))
具体函数实现
以下拉格朗日插值多项式在MATLAB中的具体实现
// 拉格朗日插值多项式在MATLAB中的具体实现
clear
clc
syms x
%------------------------------------------------------------
%Variables to be set
xx = [0,0.25,0.5,1];% The nodes(needs to be arranged in order)
y = cos(x)+sin(x); % The function needed to be interpolated
%--------------------------------------------------------------
yy = subs(y,x,xx);
num = length(xx);
dy = abs(diff(y,num));
l = [];
L = [];
R = [];
for n = 1:numtemp = xx;temp(n) =[];for m = 1:num-1l = [l (x-temp(m))/(xx(n)-temp(m))];end L = [L prod(l)*yy(n)];l = [];
endL = vpa(collect(sum(L),x));
M = eval(max(subs(dy,x,[xx(1):0.01:xx(end)])));
for n = 1:numR = [R x-xx(n)];
end
R = vpa(M/factorial(num)*abs(prod(R)));disp('The Largrange interpolation polynominal is:')
disp(L)
disp('The Bound of absolute error is:')
disp(R)
总结
使用这个脚本函数可以帮助我们在完成拉格朗日插值作业时省去很多计算时间