(一)拉格朗日插值法matlab程序代码
function [p]=Lag_polyfit(X,Y)
if size(X)~=size(Y),error('变量不匹配');end
tic
format long g
r=size(Y);n=r(2);
p=zeros(1,n);
p0=p;b=0;
W=poly(X);
dW=polyder(W);
z=polyval(dW,X);
A=[1 1];r=A;
for i=1:n
A=[1,-X(i)];
[p0,r]=deconv(W,A);
b=Y(i)/z(i);
p0=b.*p0;
p=p+p0;
end
disp(toc)
(二)复合梯形公式迭代
(1)function x=nanewton(fname,dfname,x0,e,N)
if nargin<5,N=500;end
if nargin<4,e=1e-4;end
x=x0;x0=x+2*e;k=0;
while abs(x0-x)>e&k<N,
k=k+1;
x0=x;
if feval(dfname,x0)==0,error('chucuo');else x=x0-feval(fname,x0)/feval(dfname,x0);end
disp(x)
end
if k==N,warning('yidashangxiang');end
(2)function t=natrapchange(fname,a,b,e,N)
if nargin<5,N=100; end
if nargin<4,e=1e-4;end
k=1;h=(b-a);fa=feval(fname,a);fb=feval(fname,b);
T1=h/2*(fa+fb);T2=T1/2+h/2*feval(fname,a+h/2);
while abs(T2-T1)>e,T1=T2;h=h/2;T2=T1/2+h/2*sum(feval(fname,a+h/2:h:b-0.5*h+0.001*h));k=k+1;end
if k>=N,error('chucuo');end
T2,k
(三)列主元素高斯迭代求线性方程组的解
function x=nagauss(a,b,flag)
if nargin<3,flag=0;end
n=length(b);a=[a,b];
for k=1:(n-1)
a((k+1):n,(k+1):(n+1))= a((k+1):n,(k+1):(n+1))-a((k+1):n,k)/a(k,k)*a(k,(k+1):(n+1));
a((k+1):n,k)=zeros(n-k,1);
if flag==0,a,end
end
x=zeros(n,1);
x(n)=a(n,(n+1))/a(n,n);
for k=(n-1):-1:1
x(k,:)=(a(k,(n+1))-a(k,(k+1):n)*x((k+1):n))/a(k,k);
end
(四)牛顿插值法
function [p]=newtonpoly(a)
r=size(a);n=r(1);
p=zeros(1,n);
p(1)=a(1,2);
for i=2:n
for j=3:n+1
if i>=(j-1),a(i,j)=(a(i,j-1)-a(i-1,j-1))/(a(i,1)-a(i+2-j,1));
end
end
p(i)=a(i,i+1);
end
p
(五)雅可比迭代法
function x=najacobi(a,b,x0,e,N)
if nargin<5,N=500;end
if nargin<4,e=1e-4;end
x=x0;x0=x+2*e;k=0;
while max(abs(x-x0))>e&k<N,
k=k+1;
x0=x;x=diag(diag(a))\(b-(tril(a,-1)+triu(a,1))*x0);
disp(x')
end
if k==N,warning('yidashangxian');end |