๐ฅง Monte Carlo Pi Estimator
Scatter a large number of random points inside a 1ร1 square and estimate pi from the fraction that land inside a quarter circle of radius 1 โ the classic "Monte Carlo method" simulation. A hands-on way to see randomized numerical estimation in action.
How to use
- Set the number of points to scatter (sample size).
- Press "Run simulation" to scatter random points across the square.
- Pi is estimated from the ratio of points inside the quarter circle (green) to the total (green + red).
How the calculation works
An experiment that estimates ฯ by scattering random points, known as the Monte Carlo method. Points are placed at random in a square with sides of 1. Those within distance 1 of the origin (xยฒ + yยฒ โค 1) fall inside a quarter circle of radius 1, whose area is ฯ/4. The square has area 1, so the share of points inside is roughly ฯ/4, and four times that share approximates ฯ. Estimate of ฯ = 4 ร points inside รท total points Choose between 10 and 20,000 points. Randomness comes from the browserโs cryptographic random number generator. Up to 4,000 points are drawn on screen; all of them are used in the calculation.
Worked example
Typical error for each number of points (one standard deviation) 100 points: about ยฑ0.16 (results of 3.0โ3.3 are common) 1,000 points: about ยฑ0.05 20,000 points: about ยฑ0.012 A hundred times more points only cuts the error to a tenth, because the error shrinks with the square root of the number of points.
Things to be aware of
- Monte Carlo methods approximate values that are hard to calculate directly by running many random trials. They are used in financial risk models and physics simulations.
- Results differ a little each run, even with the same number of points. Averaging several runs gives a better estimate.
- Getting many correct digits of ฯ this way would need an enormous number of points.
FAQ
Why does this method estimate pi?
A quarter circle of radius 1 has area ฯ/4, while the 1ร1 square containing it has area 1. Scattering points uniformly at random, the fraction landing inside the quarter circle approaches ฯ/4, so multiplying that fraction by 4 gives an estimate of pi.
What happens if I increase the number of points?
In general, a larger sample size tends to bring the estimate closer to the true value of pi (3.14159...), though since it's a random estimate, individual runs will still vary somewhat.
Are all the points actually drawn on screen?
To keep rendering fast, only up to 4,000 points are drawn visually. The pi estimate itself, however, is calculated using the full sample size you specify.