Bi7740: Scientific computing Introductory considerations - additional slides Vlad Popovici popovici@iba.muni.cz Institute of Biostatistics and Analyses Masaryk University, Brno Vlad Bi7740: Scientific computing Stirling’s approximation 1 % Script for Stirling's approximation. 2 % 3 4 s = @(n) sqrt(2*pi.*n).*(n./exp(1)).^n; 5 % ^−−− check "anonymous functions"! 6 7 x = 1:10; 8 f = factorial(x); 9 plot(x, (s(x) − f)./f); 10 11 return Vlad Bi7740: Scientific computing Taylor series for Euler’s number ∞ n=0 1 n! = e For correct 3 decimals, the tail (the rest of the sum, not computed) must be upper bounded by 0.0005 (why?) ∞ n=1 1 n! = k n=1 1 n! + ∞ n=k+1 1 n! = k n=1 1 n! + 1 (k + 1)! 1 + 1 k + 2 + 1 (k + 2)(k + 3) + . . . < k n=1 1 n! + 1 (k + 1)! 1 + 1 k + 1 + 1 (k + 1)2 + . . . = k n=1 1 n! + 1 (k + 1)!   1 1 − 1 k+1   = k n=1 1 n! + 1 k · k! Vlad Bi7740: Scientific computing 1 % real code would check for proper n... 2 e = @(n) (1 + sum(1 ./ factorial(1:n))); 3 fprintf('%2s\t%10s\t%10s\n', 'k', 'approx', 'tail'); 4 for k = 1:10 5 fprintf('%d\t%10.8f\t%10.8f\n', k, e(k), ... 1/(k*factorial(k))); 6 end 1 k approx tail 2 1 2.00000000 1.00000000 3 2 2.50000000 0.25000000 4 3 2.66666667 0.05555556 5 4 2.70833333 0.01041667 6 5 2.71666667 0.00166667 7 6 2.71805556 0.00023148 <−−−−− 8 7 2.71825397 0.00002834 9 8 2.71827877 0.00000310 10 9 2.71828153 0.00000031 11 10 2.71828180 0.00000003 Vlad Bi7740: Scientific computing