MATLAB: Any suggestions on what I have done wrong

debuggingwhile loop

I am attempting to find the smallest number of terms needed in the following series such that the absolute error of P – pi is less than 10^-6.
The series being S = 1/1^2 + 1/2^2 + 1/3^2…………1/n^2.
With P = sqrt(6S)
I have the following code, but have managed to create an infinite loop. Any suggestions as to where I have gone wrong?
S=1;
P=sqrt(6*S);
n=1
while abs(P-pi)>10^(-6)
n=n+1
S=S+1/(n^2)
end
disp(n)

Best Answer

The variable P in your loop condition is never being updated in the loop. So if the condition is true at the start of the loop it will always be true - hence the infinite loop