Credit: Eric Roberts
Pi (π) is a mathematical thing of true beauty. It comes up in many equations, most notably in the equation for the area of a circle, the p.d.f. of a normal distribution and finally, and oh so wonderously, in Euler's Identity
But how do we know that the value of π is 3.14159265359...? There are several ways to calculate pi. In this problem we show how to do it using darts.
This boy's name is also Pi. This problem is unrelated (other than name) to him.
Imagine throwing darts at the yellow circle bellow to the left. If you randomly throw a series of darts at the dartboard, some will land inside the yellow circle and some in the gray area outside it. If you count both the number of darts that fall inside the circle and the number that fall anywhere inside the square, the ratio of those numbers should be proportional to the relative area of the two figures.
Because the area of the circle is π and that of the square is 4, the fraction that falls inside the circle should approach π / 4.
Write a program that simulates this dart-throwing exercise to approximate π. As a hint, to generate a random number, you can use random.uniform
like this:
# gets a random number between -1 and 1 and stores it in y
y = random.uniform(-1, 1)
We can also calculate the square root of a number using math.sqrt
, like this:
# calculates the square root of x and stores it in dist
dist = math.sqrt(x)
The program you write may take 15-30 seconds to run - that's expected!
""" File: find_pi.py -------------------- Find the value of pi by throwing random darts at a unit circle inscribed in a square. The fraction that land in the circle should equal pi / 4. """ # Needed to generate random numbers import random # Needed for sqrt import math # The number of darts to throw NUM_DARTS = 20000000 def main(): print("This program takes a bit of time to run - thanks for your patience!") num_in_circle = 0 for i in range(NUM_DARTS): """ get a random x and y coordinate between (-1, -1) and (1, 1) (imagine the center of the circle is (0, 0)) """ x = random.uniform(-1, 1) y = random.uniform(-1, 1) """ test if the dart landed in the circle by calculating the length of the hypotenuse of the triangle created at this point. The radius of the circle is 1, so if the distance is more than 1 it is outside the circle. """ dist = math.sqrt(x * x + y * y) if dist <= 1: num_in_circle += 1 # Approximate pi fraction = num_in_circle / NUM_DARTS pi = fraction * 4 print(pi) if __name__ == '__main__': main()