% computeExpDumb.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 does not use the factorial function in MATLAB.
% It computes the factorial accumulatively using variable fac.
% It also computes x^k accumulatively using variable xk.
% For a slightly better version with one less operation per loop, 
% 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
    xk = 1;             % for x^k
    fac = 1;            % for the factorial at step k
    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
        xk = xk * Xvec(i);
        fac = fac * Kvec(i);
        dExp = xk / fac;        % 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) ] );
max(abs([MyExp - exp(Xvec)]))

% The run-time for this program is about 0.022 seconds. This is
% about 200 times faster than the dumber method in computeExpDumber.m

  