Ad

The goal is to estimate Pi using a Monte Carlo approach. In the 18th century, French mathematician Georges-Louis Leclerc, Comte de Buffon approximated pi by simulating throwing needles within a square that contained a circle with a diameter equal to the side of the square, and calculating the probability that they will end up in the circle.

The idea is that the ratio of needles inside the circle versus needles in the square is the same as the ratio of the area of the circle versus the area of the square.

If we use a square with a side equal to 2, its area is 4. The circle inside the square will have a diameter of 2 (therefore a radius of 1), and its area will be Pi * R**2 = Pi * 1 = Pi. So Pi / 4 = (number of needles inside the circle) / (number of needles inside the square). which means

Pi = 4 * (number of needles inside the circle) / (number of needles inside the square)

To estimate Pi, you need to randomly throw dots (same thing as a needle) in a 2 x 2 square and count the ones that will end up in the inner circle. Test with 2 millions random dots to get a fairly good estimate of Pi.

import random
def PiEstimate(runs):
    random.seed(0)   
    inner = 0
    for i in range(n):
        if random.random()**2 + random.random()**2 < 1:
            inner += 1
    return 4 * (inner / n)