mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 07:29:47 +08:00

* Updated Documentation in README.md * chore: remove wrong spelling * ci: recognize "falsy" as correct spelling * chore: fix spelling Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
22 lines
654 B
JavaScript
22 lines
654 B
JavaScript
// 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
|
|
}
|
|
|
|
// formula for pi = (ratio of number inside circle and total iteration) x 4
|
|
const pi = (circleCounter / iterations) * 4
|
|
return pi
|
|
}
|
|
|
|
export { piEstimation }
|