Pi Approximation Monte Carlo

// Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method
// Video Explanation: https://www.youtube.com/watch?v=ELetCV_wX_c

const piEstimation = (iterations = 100000) => {
  let circleCounter = 0

  for (let i = 0; i < iterations; i++) {
    // generating random points and checking if it lies within a circle of radius 1
    const x = Math.random()
    const y = Math.random()
    const radius = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))

    if (radius < 1) circleCounter += 1
  }

  // fomula for pi = (ratio of number inside circle and total iteration) x 4
  const pi = (circleCounter / iterations) * 4
  return pi
}

export { piEstimation }
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.