From 4203835cd636aed2da1ab67ddcf7b9d2eb26d9b2 Mon Sep 17 00:00:00 2001 From: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> Date: Wed, 24 Jun 2020 11:25:01 +0530 Subject: [PATCH] Added Monte Carlo Pi Approximation (#201) * Added Monte Carlo Pi Approximation * Added comments --- Maths/PiApproximationMonteCarlo.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Maths/PiApproximationMonteCarlo.js diff --git a/Maths/PiApproximationMonteCarlo.js b/Maths/PiApproximationMonteCarlo.js new file mode 100644 index 000000000..a4b3d8b81 --- /dev/null +++ b/Maths/PiApproximationMonteCarlo.js @@ -0,0 +1,25 @@ +// Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method +// Video Explaination: https://www.youtube.com/watch?v=ELetCV_wX_c + +function 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 +} + +function main () { + console.log(piEstimation()) +} + +main()