calculate pi to the nth digit in javascript

To calculate pi to the nth digit in JavaScript, we can use the following formula called the Bailey–Borwein–Plouffe (BBP) formula:

index.tsx
pi = SUM[k=0 to infinity] {
  (1 / 16^k) * (
    4 / (8k + 1) - 
    2 / (8k + 4) -
    1 / (8k + 5) -
    1 / (8k + 6)
  )
}
126 chars
9 lines

Here's a JavaScript function that uses this formula to calculate pi with a given number of decimal places:

index.tsx
function calculatePi(n) {
  let pi = 0;

  for (let k = 0; k < n; k++) {
    pi += (1 / Math.pow(16, k)) * (
      4 / (8*k + 1) -
      2 / (8*k + 4) -
      1 / (8*k + 5) -
      1 / (8*k + 6)
    );
  }

  return pi.toFixed(n - 1);
}
237 chars
15 lines

To use this function to calculate pi to, say, 100 decimal places, we can call it like this:

index.tsx
const pi = calculatePi(101); // 101 because we add 1 so the 100th digit is rounded correctly
console.log(pi); // 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193
286 chars
3 lines

gistlibby LogSnag