Since I went a little fast at the end, I am sending you the last two
Matlab programs that I've written on the board:
function s = myExp(x, tol)
s = 1; n = 1; an = 1;
while ( abs(an) > tol)
an = x^n / factorial(n);
s = s + an;
n = n + 1;
end;
function s = myExp2(x, tol)
s = 1; n = 1; an = 1;
while ( abs(an) > tol)
an = an * x / n;
s = s + an;
n = n + 1;
end;
Note that in the first program I am starting summation with term n=1,
and add the term n=0 at the initialization (s=an=1) ; this way the two
functions look more similar. The second program makes use of the
recursion relationship between terms: a(n-1) = a(n) * x / n.
Note that the two programs are formally completely equivalent; make
sure you understand what each command does. However, myExp(x,tol) only
works for values of x up to about 50, while the function myExp2(x,tol)
runs for x as large as 600. Please practice by running the two programs
for different values of x, and compare the result with the true value
exp(x).