1. 程式人生 > 其它 >數值分析(程式碼)-Lagrange插值、Newton插值、曲線擬合方法

數值分析(程式碼)-Lagrange插值、Newton插值、曲線擬合方法

技術標籤:數值分析演算法

Lagrange插值-習題4.1
習題程式碼:
main.h:
clc;clear;format long;
x0=-5:1:5;
y0=cos(x0)./sqrt(1+(sin(x0)).^2);

x=-5:0.1:5;
y=lagrange(x0,y0,x);
figure;
plot(x,y,'r--','LineWidth',3);

hold on
w=-5:0.01:5;
v=cos(w)./sqrt(1+(sin(w)).^2);
plot(w,v,'b-','LineWidth',3);

Lagrange.m:
function y=lagrange(x0,y0,x)
n=length(x0); m=length(x);
for i=1:m
z=x(i); s=0.0;
for k=1:n
p=1.0;
for j=1:n
if j~=k
p=p*(z- x0(j))/(x0(k) -x0(j));
end
end
s=p*y0(k)+s;
end
y(i)=s;
end
end

執行結果:
 

Newton插值-習題4.2
習題程式碼:
main.h:
clc;clear;format long;
x0=0.4:0.15:1;
y0=sqrt(1+([exp(x0)-exp(-x0)]./2).^2);
x=0.596;
y=newton_interpolation(x0,y0,x)
n=sqrt(1+([exp(0.596)-exp(-0.596)]./2).^2);
abs(y-n)

ewton_interpolation.m:
function np=newton_interpolation(x0,y0,x)
n=length(x0); a(1)=y0(1);
for k=1:n-1
d(k,1)=(y0(k+1)-y0(k))/(x0(k+1)-x0(k));
end
for j=2:n-1
for k=1:n-j
d(k,j)=(d(k+1,j-1)-d(k,j-1))/(x0(k+j)-x0(k));
end
end
for j=2:n
a(j)=d(1,j-1);
end
b(1)=1;
c(1)=a(1);
for j=2:n
b(j)=(x-x0(j-1)).*b(j-1);
c(j)=a(j).*b(j);
end
np=sum(c)

執行結果:
 

曲線擬合方法-習題4.8
習題程式碼:
main.h:
x0=[19 25 31 38 41]';
y0=[19 32.3 49 73.3 97.8]';
p=polyfit(x0,y0,2);
x1=19:0.05:41;
y1=polyval(p,x1);
plot(x0,y0,'*r',x1,y1,'-b');
執行結果: