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.
Best Answer