插值方法介绍
(1)分段线性插值:
对于待求的x,选取[xi,xi+1],使x属于[xi,xi+1]。再利用线性插值公式 即可求解。
(2)分段二次插值:
对于待求的x,选取与x距离最近的三个点xi-1,xi,xi+1。再利用二次插值公式 即可求解
(3)全区间上拉格朗日插值:
代码实现
分段线性插值:
function r = li( a )
%UNTITLED 此处显示有关此函数的摘要
% 此处显示详细说明
x=[0.0, 0.1, 0.195, 0.3, 0.401, 0.5];
y=[0.39894, 0.39695, 0.39142, 0.38138, 0.36812, 0.36206];
n = length(x);
m = length(y);
if n~=m
disp('error program');
return;
end
if a<x(1) || a>x(n)
disp('error input');
return;
end
for i = 2:n
if a < x(i)
z = i;
break;
end
end
b = (y(z) - y (z-1))/(x(z)-x(z-1));
r = y(z-1) + b*(a-x(z-1));
end
分段二次插值:
function r = twoint( a )
%UNTITLED 此处显示有关此函数的摘要
% 此处显示详细说明
x=[0.0, 0.1, 0.195, 0.3, 0.401, 0.5];
y=[0.39894, 0.39695, 0.39142, 0.38138, 0.36812, 0.36206];
n = length(x);
m = length(y);
if n~=m
disp('error program');
return;
end
if a<x(1) || a>x(n)
disp('error input');
return;
end
for i = 2:n
if a < x(i)
z = i;
break;
end
end
if z==2
k =3;
else
k =4;
end
if z~=2 && z~=6
p = x(z+1)-a;
q = x(z-2)-a;
if abs(p)<abs(q)
k = z+1;
else
k = z-2;
end
end
b = (y(z) - y (z-1))/(x(z)-x(z-1));
c = (y(k) - y(z))/(x(k)-x(z));
d = (c-b)/(x(k)-x(z-1));
r = y(z-1) + b*(a-x(z-1)) + d*(a-x(z-1))*(a-x(z));
end
拉格朗日插值:
function [ z ] = wlangu(a)
% 此处显示详细说明
l =ones(1,6);
q = l;
x = [0,0.1,0.195,0.3,0.401,0.5];
y=[0.39894, 0.39695, 0.39142, 0.38138, 0.36812, 0.36206];
for i = 1:6
for j =1:6
if i~=j
l(i) = l(i)*(x(i) - x(j));
q(i) = q(i)*(a-x(j));
end
end
end
z=0;
for i = 1:6
z = z + y(i)*q(i)/l(i);
end
end
应用
x | 0.0 | 0.1 | 0.195 | 0.3 | 0.401 | 0.5 |
---|---|---|---|---|---|---|
f(x) | 0.39894 | 0.39695 | 0.39142 | 0.38138 | 0.36812 | 0.35206 |
从函数表出发,计算f(0.15),f(0.31),f(0.47)的近似值
计算结果:
分段线性插值: f(0.15)=0.3944,f(0.31)=0.3802,f(0.47)=0.3619
分段二次插值: f(0.15)=0.3938,f(0.31)=0.3800,f(0.47)=0.3632
拉格朗日插值: f(0.15)=0.3944,f(0.31)=0.3802,f(0.47)=0.3619