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