javascript
// Function to estimate the value of Pi using the Monte Carlo method
function estimate_pi(points) {
// Record the start time of the function
let start_time = Date.now();
// Initialise the counter for points inside the quarter circle
let inside = 0;
// Generate the specified number of random points
for (let i = 0; i < points; i++) {
// Generate a random x-coordinate between -1 and 1
let x = Math.random()*2-1;
// Generate a random y-coordinate between -1 and 1
let y = Math.random()*2-1;
// Check if the point is inside the unit circle (x^2 + y^2 <= 1)
if (x*x + y*y <= 1) {
// If it is, increment the counter
inside++;
}
}
// Record the end time of the function
let end_time = Date.now();
// Print the elapsed time in seconds
console.log("Elapsed time: "+(end_time-start_time)/1000+" sec");
// Return the estimate of Pi (4 times the ratio of points inside the circle to the total number of points)
return 4 * (inside/points);
}
// Call the function with 1,000,000 points
pi = estimate_pi(1000000);
// Print the estimated value of Pi
console.log("π ≈ "+pi);
But why does this work? Why does pi almost equal 4 times the (inside points/all points)?
This works because it's based on the concept of probability and the geometric properties of a circle.
If we draw a square with side length 2 and inscribe a circle with radius 1 inside it, the area of the square would be 4 (2*2) and the area of the circle would be π (π*1^2).
The ratio of the area of the circle to the area of the square is π/4.
Now, if we randomly generate a large number of points within this square, the probability that any given point falls within the circle is essentially the ratio of the area of the circle to the area of the square, which is π/4.
So, in the long run, the proportion of the points that fall inside the circle (inside/points) should approach π/4.
Therefore, if we multiply this ratio by 4, we get an approximation of π.
The more points we generate, the closer our approximation should get to the actual value of π, due to the law of large numbers in probability.