3
\$\begingroup\$

Is this an efficient way to compute the value of Pi, where the limit of j \$\propto\$ accuracy?

PI = 0;
for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1);

The formula I used to write this is:

$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$

asked Dec 27, 2016 at 0:24
\$\endgroup\$
2
  • \$\begingroup\$ Could you please add a description of the mathematics behind your algorithm? That should help us to understand the merits of your approach, over, say something from here \$\endgroup\$ Commented Dec 27, 2016 at 8:34
  • \$\begingroup\$ I've edited the question, adding the formula used. \$\endgroup\$ Commented Dec 27, 2016 at 18:51

1 Answer 1

2
\$\begingroup\$

Your code will work eventually, but this series converges very very slowly. In fact, as you can read on Wolfram's web site:

... this sum converges so slowly that 300 terms are not sufficient to calculate pi correctly to two decimal places!

Here's a better way to do it which implements this function:

$$ \pi = \sum_{k=0}^\infty \frac{4(-1)^k}{2k+1} \bigg(\frac{1}{2^{2k+1}} + \frac{1}{3^{2k+1}}\bigg)$$

(function(){
 PI=0; 
 n=-4;
 for(k=0;k<100;k++) {
 z = 2*k+1;
 n *= -1;
 PI += n/z*(Math.pow(2, -z) + Math.pow(3, -z));
 }
 console.log(PI);
})();

answered Dec 27, 2016 at 21:07
\$\endgroup\$
2
  • \$\begingroup\$ I know this is code-review, but is that equation the fastest converging one, or are the limitless / ever-accurate equations. \$\endgroup\$ Commented Dec 27, 2016 at 21:47
  • \$\begingroup\$ There are equations that converge faster, but I chose this one that was close in computational complexity to the one you originally used. See Approximations of Pi on Wikipedia. \$\endgroup\$ Commented Dec 27, 2016 at 22:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.