Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Why is this break not executing for the summation of pi

1 visualización (últimos 30 días)
Alec Bischoff
Alec Bischoff el 4 de Sept. de 2020
Cerrada: MATLAB Answer Bot el 20 de Ag. de 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 comentario
Alec Bischoff
Alec Bischoff el 4 de Sept. de 2020
PrevSum/pie should eventually get below 10^-8, but my code doesn't seem to.

Respuestas (2)

Stephan
Stephan el 4 de Sept. de 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 el 4 de Sept. de 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