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)
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(100000, 3.14844)
# test.assert_equals(1000000, 3.14244)
test.assert_not_equals(2000000, 3.141634)
# You can use Test.describe and Test.it to write BDD style test groupings