1、 Write a program to computethe absolute and relative errors in Stirling’s approximation for n = 1,...,10. Doestheabsoluteerrorgrow orshrink as n increases? Does the relative error grow or shrink as n increases?
根据题意用MATLAB进行编程
代码如下
function [ y ] = errorj( x )
y = sqrt(2*pi*x)*(x/exp(1))^x-factorial(x);
end
function [ y ] = errorx( x )
y = (sqrt(2*pi*x)*(x/exp(1))^x-factorial(x))/factorial(x);
end
n = 15;
x = 1:1:n;
y1 = zeros(1,n);
y2 = zeros(1,n);
for i = 1:n
y1(i) = abs(errorj(x(i)));
y2(i) = abs(errorx(x(i)));
end
% scatter(x,y1)
% hold on
scatter(x,y2,'p')
hold on
当n取1到15时,绘制出绝对误差的图像如下所示:
当n取1到100时,绘制出绝对误差的图像如下所示:
当n取1到15时,绘制出相对误差的图像如下所示:
当n取1到100时,绘制出相对误差的图像如下所示:
观察以上四个图我们可以发现,随着n的增加绝对误差不但增大,并且增大地越来越快。而相对误差越来越小,并接近于0 。
2、
根据题意编写代码如下:
function [y] = ejinsi(x )
y = exp(1)-(1+1/10^x)^(10^x);
end
n = 10;
x = 1:1:n;
y = zeros(1,n);
for i = 1:n
y(i) = ejinsi(x(i));
end
scatter(x,y)我们可以看到随着n的增大,误差越来越小并接近于0 。而当我们取n的值为101到1020时,绘制出误差的变化趋势如下图所示
我们可以看到,大概当n取值为1015时,所计算误差出现较大变化,此时应该是计算机发生溢出所致。此时计算机已经不能运用该模型正确计算该误差的值。
(a)Use a library routine for Gaussian elimination to solve the system Ax = b,where
(b)Use the LU factorization of A already computed to solve the system Ay = c,where
without refactoring the matrix.
根据题意编写程序代码如下:
LU分解:
function [L, U] = MyLU( A )
[n1,n] = size(A);
L = zeros(n,n);
m = zeros(n,n);
if(n1 == n)
k = 1;
while k1
for i = 2:n
for j = 1:i-1
A(i,j)=0;
end
end
end
for i=1:n
m(i,i)=1;
end
L = m;
U = A;
end
function [ x ] = Fiteration( L,b )
[n1,n]=size(L);
x = zeros(n,1);
if n1==n
j = 1;
while j
后代函数:
function [ x ] = Biteration( U,b )
[n1,n] = size(U);
x = zeros(n,1);
if n1==n
j = n;
while j>0 && U(j,j)~=0
x(j,1) = b(j)/U(j,j);
for i = 1:j-1
b(i) = b(i)-U(i,j)*x(j);
end
j = j-1;
end
end
end
结果运算:
A = [2 4 -2
4 9 -3
-2 -1 7];
b = [2
8
10];
fprintf('%s\n','直接调用:')
x = inv(A)*b
fprintf('%s\n','自写函数LU分解:')
[L,U]=MyLU(A)
c = [4
8
-6];
fprintf('%s\n','直接调用:')
y1 = inv(A)*c
fprintf('%s\n','自写前代后代运算:')
front = Fiteration( L,c );
y2 = Biteration(U,front)
所以本题的结果为

371

被折叠的 条评论
为什么被折叠?



