MATLAB: Nested loops to estimate cos(pi/4)

loopstaylor series

I have written this code that is giving me an error:
true = cos(pi/4);
n = 2;
es = .5^(2-n);
x = pi/4;
ea = 1;
est = 1;
k = 1;
while(1)
for ea >= es
est = 1+x^(k*2)/factorial(k*2)*(-1)^k
ea = abs(true-est)/true*100
end
k = k+1;
end
Clearly, I do not understand the relationship of for to while loops. Can anyone help me understand?
Thank you, Mary

Best Answer

  1. You should avoid calling your variable true, as that already has a meaning in MATLAB.
  2. This line of code "for ea >= es" is not valid MATLAB syntax.
  3. Your while loop is an infinite loop; you have not specified a way to break out of it.
Most of your line of code "est = 1+x^(k*2)/factorial(k*2)*(-1)^k" matches the term in the series definition of the cosine function, but the "1+" part doesn't.
Basically you want your code to look something like this pseudocode:
1) initialize variables
2) while (the approximation is not close enough to the known value)
2a) add another term to your approximation
There's a while loop in step 2, but the condition is not 1. There is no for loop in the pseudocode. I can't say much more without simply giving you the code.
In general, if you're still unsure about how while loops work, I think one way you can understand them better is to walk through the first example (calculating factorial(10)) on its documentation page yourself, with you playing the role of MATLAB. Take a piece of paper and a pencil and "execute" each line yourself, recording the values of variables as they change on that paper. [When you reach the end statement, return to the while statement. If the while condition is not satisfied, go to the statement immediately after the end.]