Adam, your while-within-a-while construct is certainly not going to work for you. The terms "4*(-1).^n/(2*n+1)" are supposed to be added once for each successive value of n, starting with n = 0, but, as it is, your code will add this term for an unchanging n a number of times before going on to the next n because of your inner while-loop arrangement. Also the n = n+2 is wrong. It should be for each successive n, n = n + 1, not every multiple of 2.
This approximation is based on the infinite series expansion of arctan:
arctan(t) = t - 1/3*t^3 + 1/5*t^5 - 1/7*t^7 + ...
with t set to 1 giving
pi/4 = arctan(1) = 1 - 1/3 + 1/5 - 1/7 + ...
With t equal to 1 this is a very, very slowly converging series, and you should have a single while-loop with the condition that 1/(2*n+1) < 1e-6 to achieve the accuracy you desire, which will require a great many loops. You should start with n = 0 and compute your first x before adding 1 to n. (Your present code erroneously uses n = 2 for its first term.)
Note that if you were to use t = 1/sqrt(2) instead of t = 1, your series would converge much, much faster, but the added terms would have to be changed to 6*(-1)^n/(2*n+1)*t^(2*n+1), since arctan(1/sqrt(2)) = pi/6.
Note 2: Sean is teasing you. He starts with pi itself and his loop never executes.
Roger Stafford
Best Answer