diff --git a/chapters/monte_carlo/code/js/monte_carlo.js b/chapters/monte_carlo/code/js/monte_carlo.js new file mode 100644 index 000000000..b65941f10 --- /dev/null +++ b/chapters/monte_carlo/code/js/monte_carlo.js @@ -0,0 +1,29 @@ +// submitted by xam4lor +function inCircle(xPos, yPos) { + // Setting radius to 1 for unit circle + let radius = 1; + return xPos * xPos + yPos * yPos < radius * radius; +} + +function monteCarlo(n) { + let piCount = 0; + + for (let i = 0; i < n; i++) { + const pointX = Math.random(); + const pointY = Math.random(); + + if (inCircle(pointX, pointY)) { + piCount++; + } + } + + // This is using a quarter of the unit sphere in a 1x1 box. + // The formula is pi = (boxLength^2 / radius^2) * (piCount / n), but we + // are only using the upper quadrant and the unit circle, so we can use + // 4*piCount/n instead + // piEstimate = 4*piCount/n + const piEstimate = 4 * piCount / n; + console.log('Percent error is: %s%', 100 * (Math.PI - piEstimate) / Math.PI); +} + +monteCarlo(100000000); diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index c819457eb..e7fa59f94 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -41,6 +41,8 @@ each point is tested to see whether it's in the circle or not: [import:2-8, lang:"julia"](code/julia/monte_carlo.jl) {% sample lang="c" %} [import:7-9, lang:"c_cpp"](code/c/monte_carlo.c) +{% sample lang="js" %} +[import:2-6, lang:"js"](code/js/monte_carlo.js) {% sample lang="hs" %} [import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs) {% sample lang="rs" %} @@ -86,6 +88,9 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="c" %} ### C [import, lang:"c_cpp"](code/c/monte_carlo.c) +{% sample lang="js" %} +### Javascript +[import, lang:"js"](code/js/monte_carlo.js) {% sample lang="hs" %} ### Haskell [import, lang:"haskell"](code/haskell/monteCarlo.hs)