Estimating PI with Monte Carlo Simulation in Processing

Pi, π, can be computed using Monte Carlo simulation. Although that may sound complicated, it’s simpler than it sounds: Generate random points within a square, and see how many of them are inside of the circle (with the same diameter as the square’s side).

A mathematical proof of the computation goes like this: We know the ratio of the circle’s area to the square’s area is π*r*r/(2*r*2*r), since the area of a circle is π*r*r and a square is length_of_side*length_of_side, or (2*r*2*r). That equation, ratio_of_circle_to_square = π*r*r/(2*r*2*r), simplifies to ratio_of_circle_to_square = π/4. And so ratio_of_circle_to_square * 4 is equal to π.

The following code performs that simulation. It draws 100 dots at a time, and counts how many of those dots are red. The number of red dots, divided by the total number of dots, times four, is pi!

Here is the code for the monte carlo simulation:

Leave a Reply

Your email address will not be published. Required fields are marked *