Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Why is this break not executing for the summation of pi

1 vue (au cours des 30 derniers jours)
Alec Bischoff
Alec Bischoff le 4 Sep 2020
Clôturé : MATLAB Answer Bot le 20 Août 2021
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 commentaire
Alec Bischoff
Alec Bischoff le 4 Sep 2020
PrevSum/pie should eventually get below 10^-8, but my code doesn't seem to.

Réponses (2)

Stephan
Stephan le 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 le 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!

Translated by