MATLAB: How to calculate the Taylor series expansion of e^x

expansionexponentialMATLABtaylorwhile

I need to implement a script that calculate the Taylor series expansion of e^x. There are two inputs: n = the number of terms in the expansions, and tolerance = basically the percent change in adding one more term.
In other words, the tolerance = | (sum_previous – sum_new) / sum_previous | < 0.000001
So the user inputs the number of terms to be added, and they specify a tolerance. I am not sure how to get the while loops to work correctly. Here's what I have so far:
old_sum = 1;
new_sum = 0;
steps = 0;
approx = 0;
i = 0;
while (abs((old_sum-new_sum)/(old_sum)))>= tolerance
old_sum = (x^i)/myFactorial(i);
new_sum = new_sum + old_sum;
i = i + 1;
steps = steps + 1;
end

Best Answer

I changed things slightly. Look carefully at the changes I made.
tolerance = 0.000001;
old_sum = 1;
new_sum = 0;
current_term = inf;
iter = 0;
while abs(current_term/old_sum) >= tolerance
old_sum = new_sum;
current_term = (x^iter)/myFactorial(iter);
new_sum = new_sum + current_term;
iter = iter + 1;
end
steps = iter;
Note that the difference between the two approximations is the variable now named current_term. So I could have written the test to work on this:
abs((new_sum - old_sum)/old_sum)
but we know what the difference in the numerator is already.
As far as incrementing both i AND the variable steps, WHY? As well, it is a bad idea to use the variable i, since i already exists in MATLAB as sqrt(-1). Better to form good habits early in your career. So I changed i to iter.
I tested the code above. It works. But be careful, for large x, it will be a problem. You should know that already, if you have discussed convergence of series in class.
Related Question