Search code examples
javascriptmathpi

Accurately calculating PI to x places in JavaScript


I know this question has been asked before but I couldn't exactly find the answer. I'm trying to make a function that accurately calculates pi to x places. Here's my code so far:

  function odd(num) { return num % 2;}
  var pi = 3;
  var x=2;
  for (var acc = 1; acc < 30000; acc++) {
    if (Odd(acc)) {
      pi = pi + (4/(x * (x+1) * (x+2)));
    } else {
      pi = pi - (4/(x * (x+1) * (x+2)));
    }
    x=x+2;
  }
  console.log(pi);

This works, but how do I specify the length while also making sure it stays accurate?


Solution

  • As this series is alternating, the error of a partial sum is always smaller than the absolute value of the next term. So essentially the error after n terms is about 1/(2*n^3).

    Additionally, you will get an error of magnitude n*1e-16 for the floating point operations, so the best achievable result will be for about n=1e4 with an error of magnitude 1e-12.


    On second thought, summing from smallest to largest term will avoid the accumulation of large floating point errors as the next error is in magnitudes about the magnitude of the next term times the machine epsilon. Thus the total error will have a bound proportional to the absolute sum, which is a finite value smaller 5e-15. This reverse summation should allow the almost error-free calculation until n^3=10^15 or n=10^5 with 15 correct places.