Any suggestions on what I have done wrong?

1 次查看(过去 30 天)
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)

采纳的回答

David Fletcher
David Fletcher 2018-3-31
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by