Info

This question is closed. Reopen it to edit or answer.

Why is this break not executing for the summation of pi

1 view (last 30 days)
pie = 0;
for k = 0:100
eqn = sqrt(12)*((-3)^(-k)/((2*k)+1));
PrevSum = pie;
pie = pie + eqn;
if PrevSum ~= 0 & (PrevSum/pie) < (10^(-8))
k
return
end
end
pie
PrevSum/pie
>>
pie =
3.141592653589794
ans =
1
  1 Comment
Alec Bischoff
Alec Bischoff on 4 Sep 2020
PrevSum/pie should eventually get below 10^-8, but my code doesn't seem to.

Answers (2)

Stephan
Stephan on 4 Sep 2020
You never reach the value of your ratio of PrevSum/pie. I inserted 2 lines, the first saves the ratio in every single run of your loop, the second plots the ratio over the variable k. This helps you to understand whats going wrong. You will have to think about another criteria to stop the loop, when the maximum deviation is reached:
pie = 0;
for k = 0:100
eqn = sqrt(12)*((-3)^(-k)/((2*k)+1));
PrevSum = pie;
pie = pie + eqn;
error_rate(k+1) = PrevSum/pie;
if PrevSum ~= 0 && (PrevSum/pie) < (10^(-8))
k
return
end
end
pie
PrevSum/pie
plot(0:100,error_rate)

Alan Stevens
Alan Stevens on 4 Sep 2020
PrevSum/pie should tend to 1. abs(PrevSum - pie) should get smaller than 10^-8.
Try
pie = 0;
k = 0;
err = 1;
while err>10^-9
PrevSum = pie;
eqn = sqrt(12)*((-3)^(-k)/((2*k)+1));
pie = PrevSum + eqn;
err =abs(PrevSum/pie - 1);
k = k+1;
end
format long
pie
PrevSum/pie
abs(PrevSum - pie)

Community Treasure Hunt

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

Start Hunting!