MATLAB: Help with while loop

taylor serieswhile loop

Hello,
I have to create a program that will find the taylor series expansion at an arbitrary value x. I also have to find the relevant error of the series expansion from the true exp.
Create a MATLAB program to compute this series and stop at %error < 3%. Display the value of the series approximation and how many terms that you used to calculate this value.
x=1.5;
y=0;
n=0;
error=0;
while(error>3)
if n<2
f=1;
elseif n>=2
f=f*n;
end
y=y+(x^n/(f));
error=((exp(x)-y)/exp(x))*100;
n=n+1;
end
disp(n-1)
disp(error)
This is currently what I have but my program will only compute for the first n. I can not seem to see what is going wrong and would appreciate any hints.

Best Answer

You were pretty close, but there are a couple of mistakes.
  1. You start out the error at zero, then ask the loop to run only when the error is greater than 3....
  2. You are not actually calculating the factorial for each new value of n.
  3. You need to use the absolute value when calculating the error.
x=1.5;
y=0;
n=0;
ER=100; % Don't name a variable 'error'. Start >3 so loop runs!
while(ER>3)
f = 1;
for ii=2:n
f=f*ii;
end
y = y+(x^n/(f));
ER = (abs(exp(x)-y)/exp(x))*100;
n=n+1;
end
disp(n-1)
disp(ER)