Monte Carlo methods can be used to calculate an approximation to the value of an
integral.
(Most problems that Monte Carlo solves can be stated in terms of a relevant integral).
Integrals can be visualized as calculating an area or volume that is delineated by some function.
Assuming the integral is bounded in space, the method involves generating a set of random points
within a set of bounds in that space. Then the percentage of volume that the desired integral takes within
the bounds is given by the percentage of points that fall within the function value diveied by the total
number of points generated.
Calculating Pi
A simple example is the calculation of pi by monte carlo methods. The method defines a square within which a number of random points is generated.
A circle of a prespecified radius is defined. The area of the circe is {% \pi r^2 %}, and the area of the square is {% length \times width %}.
Then {% \pi r^2 / length \times width %} is approximately equal to the number of points that fall within the circle to the total number of
points generated.
In the sample code below, we take the square to be of side length 2, and the radius of the circle to be 1.
let sum1 = 0;
let sum2 = 0;
for(let i=0;i<500000;i++){
let x = 2*Math.random() - 1;
let y = 2*Math.random() - 1;
if(x*x + y*y <= 1) sum1+=1
else sum2+=1;
}
let pi = 4*sum1/(sum2+sum1);
$console.log(pi);