How to resolve the algorithm Monte Carlo methods step by step in the Jsish programming language
How to resolve the algorithm Monte Carlo methods step by step in the Jsish programming language
Table of Contents
Problem Statement
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be
π
/
4
{\displaystyle \pi /4}
. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately
π
/
4
{\displaystyle \pi /4}
.
Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number
π
{\displaystyle \pi }
is not built-in, we give
π
{\displaystyle \pi }
as a number of digits:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Monte Carlo methods step by step in the Jsish programming language
Source code in the jsish programming language
/* Monte Carlo methods, in Jsish */
function mcpi(n) {
var x, y, m = 0;
for (var i = 0; i < n; i += 1) {
x = Math.random();
y = Math.random();
if (x * x + y * y < 1) {
m += 1;
}
}
return 4 * m / n;
}
if (Interp.conf('unitTest')) {
Math.srand(0);
; mcpi(1000);
; mcpi(10000);
; mcpi(100000);
; mcpi(1000000);
}
/*
=!EXPECTSTART!=
mcpi(1000) ==> 3.108
mcpi(10000) ==> 3.1236
mcpi(100000) ==> 3.13732
mcpi(1000000) ==> 3.142124
=!EXPECTEND!=
*/
You may also check:How to resolve the algorithm Pangram checker step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Variable-length quantity step by step in the PL/I programming language
You may also check:How to resolve the algorithm Search a list step by step in the REBOL programming language
You may also check:How to resolve the algorithm Calkin-Wilf sequence step by step in the 11l programming language
You may also check:How to resolve the algorithm Reverse words in a string step by step in the Gambas programming language