calculate pi to the nth digit without limits in javascript

To calculate Pi to the nth digit without limits in JavaScript, we can use the Leibniz formula for Pi, which is an infinite series:

Pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...

We can compute this series to as many terms as we need using a loop. However, we also need a way to handle arbitrarily large numbers in JavaScript, since the built-in Number type has a limited precision. To achieve this, we can use a library like big-integer to perform calculations with big integers. Here's how we can implement the algorithm:

index.tsx
const bigInt = require('big-integer');

function calculatePi(n) {
  let pi = bigInt.zero;

  for (let i = 0; i < n; i++) {
    let sign = i % 2 === 0 ? 1 : -1;
    let term = bigInt(1).div(2*i+1).times(sign);
    pi = pi.plus(term);
  }

  // multiply by 4 to get Pi
  pi = pi.times(4);

  return pi.toString();
}
314 chars
17 lines

Here, we use the bigInt library to represent arbitrary-precision integers. We initialize the sum pi to 0, and then loop over the desired number of terms, computing each term according to the Leibniz formula and adding it to pi. Finally, we multiply pi by 4 to get the actual value of Pi, and return it as a string.

Note that this implementation may not be particularly efficient for very large values of n, since we are computing and storing all terms of the series. There are other algorithms that converge faster, such as the Bailey–Borwein–Plouffe formula or the Gauss–Legendre algorithm, but they are more complex to implement.

gistlibby LogSnag