Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4203835

Browse files
Added Monte Carlo Pi Approximation (TheAlgorithms#201)
* Added Monte Carlo Pi Approximation * Added comments
1 parent d8eee0c commit 4203835

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

‎Maths/PiApproximationMonteCarlo.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method
2+
// Video Explaination: https://www.youtube.com/watch?v=ELetCV_wX_c
3+
4+
function piEstimation (iterations = 100000) {
5+
let circleCounter = 0
6+
7+
for (let i = 0; i < iterations; i++) {
8+
// generating random points and checking if it lies within a circle of radius 1
9+
const x = Math.random()
10+
const y = Math.random()
11+
const radius = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
12+
13+
if (radius < 1) circleCounter += 1
14+
}
15+
16+
// fomula for pi = (ratio of number inside circle and total iteration) x 4
17+
const pi = (circleCounter / iterations) * 4
18+
return pi
19+
}
20+
21+
function main () {
22+
console.log(piEstimation())
23+
}
24+
25+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /