% MatLab function for part 3 of the question for the CSC 336 tutorial % on 29 Sept. 2007. % % This function approximates e^x by summing the series % sum = 1 + |x| + |x|^2/2! + |x|^3/3! + ... % from left to right until the value of the sum does not change % and then setting the apprxomiation to e^x to sum if x >= 0 or % or 1/sum if x < 0. % % K.R.J. 24 Sept. 2007 function y = exp2(x) sumold = 0; sum = 1; xabs = abs(x); k = 0; term = 1; % term will be |x|^k/k! We increment each time around the % while look to avoid having to recompute |x|^k/k! while sumold ~= sum, sumold = sum; k = k+1; term = term * xabs / k; sum = sum + term; end if x >= 0 y = sum; else y = 1/sum; end