Skip to content

Commit 8367b34

Browse files
xam4lorButt4cak3
authored andcommitted
Added monte carlo javascript example (#175)
1 parent 69ccdd6 commit 8367b34

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// submitted by xam4lor
2+
function inCircle(xPos, yPos) {
3+
// Setting radius to 1 for unit circle
4+
let radius = 1;
5+
return xPos * xPos + yPos * yPos < radius * radius;
6+
}
7+
8+
function monteCarlo(n) {
9+
let piCount = 0;
10+
11+
for (let i = 0; i < n; i++) {
12+
const pointX = Math.random();
13+
const pointY = Math.random();
14+
15+
if (inCircle(pointX, pointY)) {
16+
piCount++;
17+
}
18+
}
19+
20+
// This is using a quarter of the unit sphere in a 1x1 box.
21+
// The formula is pi = (boxLength^2 / radius^2) * (piCount / n), but we
22+
// are only using the upper quadrant and the unit circle, so we can use
23+
// 4*piCount/n instead
24+
// piEstimate = 4*piCount/n
25+
const piEstimate = 4 * piCount / n;
26+
console.log('Percent error is: %s%', 100 * (Math.PI - piEstimate) / Math.PI);
27+
}
28+
29+
monteCarlo(100000000);

chapters/monte_carlo/monte_carlo.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ each point is tested to see whether it's in the circle or not:
4141
[import:2-7, lang:"julia"](code/julia/monte_carlo.jl)
4242
{% sample lang="c" %}
4343
[import:7-9, lang:"c_cpp"](code/c/monte_carlo.c)
44+
{% sample lang="js" %}
45+
[import:2-6, lang:"js"](code/js/monte_carlo.js)
4446
{% sample lang="hs" %}
4547
[import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs)
4648
{% sample lang="rs" %}
@@ -86,6 +88,9 @@ Feel free to submit your version via pull request, and thanks for reading!
8688
{% sample lang="c" %}
8789
### C
8890
[import, lang:"c_cpp"](code/c/monte_carlo.c)
91+
{% sample lang="js" %}
92+
### Javascript
93+
[import, lang:"js"](code/js/monte_carlo.js)
8994
{% sample lang="hs" %}
9095
### Haskell
9196
[import, lang:"haskell"](code/haskell/monteCarlo.hs)

0 commit comments

Comments
 (0)