10 Million Darts of π

An instructive, ludicrously-simple Monte Carlo simulation in Python

Tanae
2 min readApr 6, 2020
Photo by Marc A on Unsplash

This exercise introduces the Monte Carlo Method and the Law of Large Numbers using the mathematical toolkit of an eighth-grade student. As for the programming aspect, an elementary understanding of Python will suffice, though I provide some ways to eliminate this prerequisite near the end.

When self-learning or teaching others, it is sometimes important to step away from the jargon and advanced knowledge in order to develop understanding. My hope is that this exercise demonstrates the power of simple, intuitive thinking in explaining seemingly-complex concepts.

The ‘dartboard’ on a 2-dimensional coordinate plane, graphed with Desmos

The area of a circle with radius 1 is π. Such a circle fits within a square of side length 2. Envisioning the coloured area above as a dart board, randomly-thrown darts will land both in the green area within the circle and the red area outside of its bounds. The fraction of darts landing in the green area is equal to the ratio of the area of the circle (π) to the area of the square (4).

The ratio of the darts landing in the green area to the total darts thrown is therefore equal to π/4. If the darts were thrown only in the first quadrant (where both x and y are positive), the same result would occur as the area ratio remains unchanged.

import random
import math
#generating a random coordinate pair within first quadrant
randomcoord=[random.random(),random.random()]
#counting the number of trials inside bounds of circle
inboundscount=0
#number of trials
samplesize=10000
#asking whether an inputted coordinate pair is within the circle
def inbounds(coord):
if coord[0]**2+coord[1]**2 <= 1:
return True
else:
return False
#running inbounds() for the preset number of trials
def montecarlo(samplesize):
for i in range (1, samplesize):
randomcoord=[random.random(),random.random()]
global inboundscount
if inbounds(randomcoord)==True:
inboundscount+=1
montecarlo(samplesize)print("Pi is estimated to be {} (sample size of {}).".format(4*inboundscount/samplesize,samplesize))#Sample output: Pi is estimated to be 3.1512 (sample size of 10000).

The above code carries out the aforementioned experiment with the added bonuses of speed and (pseudo)randomness. The positive correlation between sample size and the accuracy of the estimate can be observed by changing the number of trials.

If the primary goal is mathematical understanding rather than programming practice, this concept could just as easily be implemented in a block-type programming software like Scratch.

Alternatively, you could do away with the coding entirely and find π via Monte Carlo simulation by throwing hot dogs.

On second thought, I should have led with that…

--

--

No responses yet