Approximates sin(x) by its expansion x input argument e input argument for the stopping criterion res final approximation abserr final absolute error relerr final relative error n number of iterations needed to reach the stopping criterion
0001 function [res, abserr, relerr, n]= sinbysum(x, e) 0002 % Approximates sin(x) by its expansion 0003 % x input argument 0004 % e input argument for the stopping criterion 0005 % res final approximation 0006 % abserr final absolute error 0007 % relerr final relative error 0008 % n number of iterations needed to reach the stopping criterion 0009 0010 res = x; % initialize the result, for small values of x sin(x) is 0011 % approximately x 0012 d = abs(x); % d holds by how much the approximation has changed in 0013 % one iteration in modulus 0014 n = 1; % the iteration count is initialised to 1 since res = x is 0015 % the first approximation 0016 while d > e 0017 n = n+1; 0018 m = 2*n-1; 0019 temp = x^(m)/factorial(m); % element of the sum to be subtracted 0020 % or added 0021 d = abs(temp); 0022 if mod(n,2) == 0 % even iteration number, we have to subtract 0023 res = res - temp; 0024 else % odd iteration number, we have to add 0025 res = res + temp; 0026 end 0027 end 0028 truesol = sin(x); 0029 abserr = res - truesol; 0030 if abs(truesol) > 1e-12 % not comparing to zero because of possible 0031 % rounding errors 0032 relerr = abserr/truesol; 0033 else 0034 disp('relative error not computed, the solution is too small'); 0035 end