二、 Matlab程序
1.%构造lagrange插值函数
function y1=lagrange(x,y,x1) m=length(x); n=length(y); p=length(x1); if m~=n error; end s=0; for k=1:n t=ones(1,p); for j=1:n if j~=k,
t=t.*(x1-x(j))/(x(k)-x(j)); end end
s=s+t*y(k); end y1=s;
%在界面中运行
x=[1940 1950 1960 1970 1980 1990];
y=[132.165 151.326 179.323 203.302 226.542 249.633]; y1930=lagrange(x,y,1930); y1965=lagrange(x,y,1965); y2010=lagrange(x,y,2010);
fprintf('the population in 1930 is %f\\n',y1930) fprintf('the population in 1965 is %f\\n',y1965) fprintf('the population in 2010 is %f\\n',y2010)
2.
x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19];y=[0.898 2.38 3.07 1.84 2.02 1.94 2.22 2.77 4.02 6.53 10.9 16.5 22.5 35.7 50.6 61.6 81.8];
4.76 5.46
yi=log(y); a=polyfit(x,yi,1); ai=exp(a(2)); xm=1:0.05:19; ym=ai*exp(a(1).*xm); plot(x,y,'*k',xm,ym,'-y') fprintf('a is %f\\n',ai) fprintf('b is %f\\n',a(1))
3. (1)
%构造复合梯形积分公式
function I=tquad(x,y) n=length(x) m=length(y) if n~=m error end
h=(x(n)-x(1))/(n-1) a=[1 2*ones(1,n-2) 1] I=h/2*sum(a.*y) End
%用梯形公式计算积分
format long x=0:0.1:1; y=x./(4+x.^2); I1=tquad(x,y)
%计算积分
format long
f=inline('x./(4+x.^2)'); I=quadl(f,0,1)
%作误差与n的关系曲线 %构造函数
function I=tq(k) x=0:0.9/k:1;
y=x./(4+x.^2); n=length(x); m=length(y); if n~=m error; end
h=(x(n)-x(1))/(n-1); a=[1 2*ones(1,n-2) 1]; I=h/2*sum(a.*y); end
%计算并作图
n=1:100; t1=ones(1,100); for k=1:100
t1(k)=t1(k)*tq(k); end
f=inline('x./(4+x.^2)'); I=quadl(f,0,1); t2=I-t1;
plot(n,t2,'*k',n,t2,'-y') (2)
%构造复合辛普森积分公式
function I=simpsion(x,y) m=length(x); n=length(y); if m~=n error; end
if rem(n-1,2)~=0 I=tquad(x,y); return; end; N=(n-1)/2; h=(x(n)-x(1))/N;
a=zeros(1,n); for k=1:N
a(2*k-1)=a(2*k-1)+1; a(2*k)=a(2*k)+4; a(2*k+1)=a(2*k+1)+1; end
I=h/6*sum(a.*y); End
%分别计算积分
format long x=0:0.1:1; y=x./(4+x.^2);
isimosion=simpsion(x,y) itquad=tquad(x,y)
三、 结果
通过Matlab程序运行结果如下: 1.
the population in 1930 is 169.649000 the population in 1965 is 191.767359 the population in 2010 is 171.351000
由于lagrange插值不能准确估计范围外的数值,因此1930年和2010年的误差较大。 2.
a is 0.681361 b is 0.230620
3. (1)I1 =
0.111463380815167 I =