Estimating Pi in 14 Lines of Python Code

Here’s a fun method for estimating Pi in about 14 lines of Python code. Imagine building yourself a dartboard that looks like this:

0-F7KjgsAWAlEyg9j3.jpg

The area of the circular part of the dart board is:

And the area of the entire square of this dart board is:

Now think about throwing some darts at this board. What’s the probability each dart will land inside the circle? Easy enough — it’s the area of the circle divided by the area of the square, or

0-aQq8IQEIn_1vfqIU..gif

Now we have a really simple expression we can use in practice to estimate Pi to whatever precision we need. Imagine throwing darts at the board — randomly, as you’ll need a uniform distribution of throws for this to work. Count the percentage of your dart throws that hit inside the circle. That percentage is Pr(dart in circle). To estimate Pi, multiply that percentage by four.

Here is a simple Python simulation for 10,000 dart throws. The bad news? It converges to Pi painfully slowly, so not a great in-production algo. But it is a fun teaching tool for illustrating the many surprising links between stats, geometry, and programming.