wenskya
2011-09-14 15:58:46 UTC
function ssum=sinser(x,tol,n)
%sinser evaluate the series representation of the sine function
%
% Input: x=argument of the sine function, i.e., compute sin(x)
% tol=tolerance on accumulated sum. Default: tol=5e-9
%n=maximum number of terms. Default: n=15
%
% Output: ssum= value of series sum after nterms or tolerance is met
term=x; ssum=term; % Initialize series
fprint('series approximation to sin(%f)\n\n k term ssum\n',x);
fprint('%3d %11.3e %12.8f\n',1,term,ssum);
for k=3:2:(2*n-1)
term=-term*x*x/(k*(k-1)); % Next term in the series
ssum=ssum+term;
fprint('%3d %11.3e %12.8f\n',k,term,ssum);
if abs(term/ssum)
fprintf('\nTruncation error after %d terms is %g\n\n',(k+1)/2,abs(ssum-sin(x)));
ssum=sinser(pi/6, 5e-9,15);