% computeExpDumber.m
% Compute the exponential function, exp(x), by summing its Taylor series.
% Calculation is performed on a vector of input values of x.
% 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 uses the factorial function & the power operation in MATLAB.
% For a better version that does not use either of these functions,
% see computeExpDumb.m. Even better yet see computeExp.m.
% K. Ming Leung, October 5, 2008.

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

Xvec = transpose(0.1:0.0002:2);     % input vector of x (radians)
lenX = length(Xvec);                % number of x values
tic
MyExp = ones(lenX,1);   % initialize the sum to 1 (1st term of series)
Kvec = zeros(lenX,1);   % initialize vector for the no. of terms
for i = 1:lenX          % loop through each value of x
    Kvec(i) = 0;        % initial counter for the no. of terms
    dExp = 1;           % value of the next term of the series
    while abs(dExp) > tol       % loop till max error < tol
        Kvec(i) = Kvec(i) + 1;  % increment the summation index
        dExp = Xvec(i)^Kvec(i) / factorial(Kvec(i)); % next term in the series
        MyExp(i) = MyExp(i) + dExp;     % add this term to the sum         
    end
end
toc
% display a table showing the x value, the no. terms summed, 
% the computed values of exp(x), and the exact values of exp(x):
%disp( [ Xvec Nvec MyExp exp(Xvec) ] );
% The run-time for this program is about 4.96 seconds.
    
  