Describing a sum with a while loop

Hello I was woundering how you do this formula for pi as variable s in a while loop.
For example;
n=a big number
s=0
while s<=pi
s=s+n
end
Thanks!

답변 (1개)

Bob Thompson
Bob Thompson 2019년 9월 30일

0 개 추천

I'm pretty sure that adding a big number to 0 will bump you over pi on the first iteration, but maybe that's just me. I would do something more like the following:
s = 0;
tmp = 0;
k = 0;
while s<=pi
k = k + 1;
tmp = tmp + (-1/3)^k/(2*k+1);
s = sqrt(12)*tmp;
end

댓글 수: 1

Steven Lord
Steven Lord 2019년 9월 30일
Of course, this approach assumes you know the answer you're trying to compute.
To approximate pi without actually knowing pi you probably want to loop until the step you're adding is "small enough" for some definition of "small enough".

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2019년 9월 30일

댓글:

2019년 9월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by