This function performs a Monte Carlo simulation to estimate the value of Pi by randomly generating points within a square and checking how many fall within an inscribed circle's quadrant.
/**
* monteCarloPiEstimation
*
* Estimates the value of Pi using the Monte Carlo method.
* The method works by simulating random points within a unit square (0,0) to (1,1).
* An inscribed quarter-circle within this square has a radius of 1.
* The ratio of points falling inside the quarter-circle to the total number of points
* is proportional to the ratio of the quarter-circle's area to the square's area.
* Area of square = 1 * 1 = 1
* Area of quarter-circle = (1/4) * Pi * r^2 = (1/4) * Pi * 1^2 = Pi / 4
* So, (points_in_circle / total_points) = (Pi / 4) / 1
* Which implies Pi = 4 * (points_in_circle / total_points).
*
* @param {number} numSimulations The total number of random points to generate for the simulation.
* A higher number generally leads to a more accurate estimation.
* @returns {number} The estimated value of Pi.
*/
function monteCarloPiEstimation(numSimulations) {
// Validate input: Ensure numSimulations is a positive integer.
if (typeof numSimulations !== 'number' || numSimulations <= 0 || !Number.isInteger(numSimulations)) {
console.error('Error: numSimulations must be a positive integer.');
return NaN;
}
let pointsInsideCircle = 0;
// Run the simulation for the specified number of iterations.
for (let i = 0; i < numSimulations; i++) {
// Generate random x and y coordinates between 0 and 1.
// These represent points within the unit square (0,0) to (1,1).
const x = Math.random();
const y = Math.random();
// Calculate the distance from the origin (0,0) to the point (x,y).
// We are interested if the point falls within the quarter-circle of radius 1.
// The equation of a circle centered at the origin is x^2 + y^2 = r^2.
// For a unit circle, r=1, so we check if x^2 + y^2 <= 1.
const distanceSquared = x * x + y * y;
if (distanceSquared <= 1) {
// If the distance squared is less than or equal to 1, the point falls
// inside or on the boundary of the quarter-circle.
pointsInsideCircle++;
}
}
// Calculate the estimated value of Pi.
// Pi is approximately 4 * (number of points inside circle / total number of simulations).
const estimatedPi = 4 * (pointsInsideCircle / numSimulations);
return estimatedPi;
}
// Example Usage:
// console.log('Estimating Pi with 1,000 simulations:', monteCarloPiEstimation(1000));
// console.log('Estimating Pi with 10,000 simulations:', monteCarloPiEstimation(10000));
// console.log('Estimating Pi with 1,000,000 simulations:', monteCarloPiEstimation(1000000));
// console.log('Estimating Pi with 10,000,000 simulations:', monteCarloPiEstimation(10000000));