MATLAB Answers

Describing a sum with a while loop

4 views (last 30 days)
Jonathan Larsson
Jonathan Larsson on 30 Sep 2019
Commented: Steven Lord on 30 Sep 2019
Hello I was woundering how you do this formula for pi as variable s in a while loop.
For example;
n=a big number
while s<=pi


Sign in to comment.

Answers (1)

Bob Nbob
Bob Nbob on 30 Sep 2019
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;

  1 Comment

Steven Lord
Steven Lord on 30 Sep 2019
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".

Sign in to comment.