% computeSin3.m
% Compute the sine of an angle (in radians) by summing its Taylor 
% series up to m terms.
% Calculation is performed on a vector of input angles.
% The maximum error allowed is specified by tol .
% Total no. of terms needed to be summed to achieve this error level 
% is reported.
% Comparison with exact values is also shown.
% This version is similar to the earlier program computeSin except that
% this version does not use the factorial or the power function,
% and is therefore more efficient.
% K. Ming Leung, October 6, 2008.

clear; format long e;
tol = 1e-6;     % tolerance (maximum error allowed)

Xvec = transpose(0.1:0.2:pi/2);     % input vector of x (radians)
lenX = length(Xvec);                % number of x values
MySin = Xvec;                       % initialize vector my sin values
Nvec = zeros(lenX,1);   % initialize vector for the no. of terms
for i = 1:lenX
    Nvec(i) = 0;        % initial counter for the no. of terms
    dSin = Xvec(i);           % change in the computed value of my sin
    x2 = Xvec(i)^2;     %  
    k = 3
    while abs(dSin) > tol       % loop till max error < tol
        dSin = - dSin * x2 / (k * (k-1)); % next term to sum
        MySin(i) = MySin(i) + dSin;     % add this term to my sin 
        k = k + 2;
        disp('x');
    end
    Nvec(i) = (k - 1)/2;
end
% display a table showing the x value, the no. terms summed, 
% the computed values of sin, and the exact values of sin:
disp( [ Xvec Nvec MySin sin(Xvec) ] );
max(abs(MySin - sin(Xvec)))
    






