calculate pi in javascript

One common way to approximately calculate pi in JavaScript is by using the Monte Carlo method.

index.tsx
function approximatePi(iterations) {
  let insideCircle = 0;
  let total = 0;

  for (let i = 0; i < iterations; i++) {
    const x = Math.random();
    const y = Math.random();
    const distance = Math.sqrt(x * x + y * y);
    if (distance <= 1) {
      insideCircle++;
    }
    total++;
  }

  // pi = 4 * (number of points inside circle / total number of points)
  const pi = 4 * (insideCircle / total);

  return pi;
}

console.log(approximatePi(10000)); // Example output: 3.146
486 chars
22 lines

This function generates iterations random points between 0 and 1 on both the x and y axes, checks if each point falls within a unit circle in the graph's center, and then approximates pi based on the ratio of points inside the circle to the total number of generated points multiplied by 4. The higher the number of iterations, the more accurate the approximation.

gistlibby LogSnag