3. Stirling approximation is a very useful approximation for the factorials. It
ID: 2256534 • Letter: 3
Question
3. Stirling approximation is a very useful approximation for the factorials. It tells us that where an ~ b,' means limnoo@n/br.-1. (a) Use the Matlab command line or write an m-file to compute both n! and Sn for n -2,3,4,5,6,7,8 (b) For each n compare the Stirling approximation and n! by evaluating both In! -Snl and(Mtlah command for absolute value function is abs(x)). What do you observe as n getting larger (Hint: you may find convenient to set n as an variable. If you use the command window up/down arrow on your keyboard handy to change the value of n.)Explanation / Answer
Matlab Code
clc
clear all
n=5;
factorial=ones(n+1,1);
v=zeros(n,1);
S=zeros(n,1);
if (n <1)
factorial='error';
else
for i=1:1:n
v(i)=i;
factorial(i+1)=factorial(i)*v(i);
S(i)=sqrt(2*pi*i)*(i/exp(1))^i;
end
end
factorial=factorial(2:end)
v
S
A=[v,factorial,S]
Absolute_Error=abs(A(:,2)-A(:,3))
Relative_Error=zeros(n,1);
for i=1:n
Relative_Error(i)=Absolute_Error(i)/S(i);
end
Relative_Error=Relative_Error'
A=[A,Absolute_Error,Relative_Error]
B=A(2:end,:)
Output
factorial =
1
2
6
24
120
v =
1
2
3
4
5
S =
0.9221
1.9190
5.8362
23.5062
118.0192
A =
1.0000 1.0000 0.9221
2.0000 2.0000 1.9190
3.0000 6.0000 5.8362
4.0000 24.0000 23.5062
5.0000 120.0000 118.0192
Absolute_Error =
0.0779
0.0810
0.1638
0.4938
1.9808
Relative_Error =
0.0844
0.0422
0.0281
0.0210
0.0168
A =
1.0000 1.0000 0.9221 0.0779 0.0844
2.0000 2.0000 1.9190 0.0810 0.0422
3.0000 6.0000 5.8362 0.1638 0.0281
4.0000 24.0000 23.5062 0.4938 0.0210
5.0000 120.0000 118.0192 1.9808 0.0168
B =
2.0000 2.0000 1.9190 0.0810 0.0422
3.0000 6.0000 5.8362 0.1638 0.0281
4.0000 24.0000 23.5062 0.4938 0.0210
5.0000 120.0000 118.0192 1.9808 0.0168
For n=-1
Matlab code
clc
clear all
n=-1;
factorial=ones(n+1,1);
v=zeros(n,1);
S=zeros(n,1);
if (n <1)
factorial='error';
else
for i=1:1:n
v(i)=i;
factorial(i+1)=factorial(i)*v(i);
S(i)=sqrt(2*pi*i)*(i/exp(1))^i;
end
end
factorial=factorial(2:end)
v
S
A=[v,factorial,S]
Absolute_Error=abs(A(:,2)-A(:,3))
Relative_Error=zeros(n,1)
for i=1:n
Relative_Error(i)=Absolute_Error(i)/S(i);
end
Relative_Error=Relative_Error'
A=[A,Absolute_Error,Relative_Error]
B=A(2:end,:)
Output
factorial =
rror
v =
Empty matrix: 0-by-1
S =
Empty matrix: 0-by-1
A =
rror
Absolute_Error =
3
Relative_Error =
Empty matrix: 0-by-1
Relative_Error =
Empty matrix: 1-by-0
A =
rror
B =
Empty matrix: 0-by-5
As n getting larger we observe that the error becomes larger with the factorial and sterling's approximation.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.