Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Why is this break not executing for the summation of pi

1 回表示 (過去 30 日間)
Alec Bischoff
Alec Bischoff 2020 年 9 月 4 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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 件のコメント
Alec Bischoff
Alec Bischoff 2020 年 9 月 4 日
PrevSum/pie should eventually get below 10^-8, but my code doesn't seem to.

回答 (2 件)

Stephan
Stephan 2020 年 9 月 4 日
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 2020 年 9 月 4 日
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