A simple idea for computing π

Idea: generate N points in the 1x1 square in the first quadrant


   . |
   . |
 0   1   2   3

Compute the number of points which fall within the unit circle centered at 1.

The quarter-circle that's the part of the unit circle that's in the first quadrant has area 14π×12=14π, and the unit square has area 1, so about 14π of the random points should be within the quarter-circle.

We compute the ratio of the number of points in the quarter circle and the total number of random points, multiply it by 4, and get π.

To test whether the point (x,y) is within the unit circle, we test whether x2+y2<1 (since points inside the unit circle all are less than 1 unit away from the origin, so that x2+y2<1.

A small preliminary note on generating random numbers

We can use random.random() to generate random numbers in the interval [0,1). Every time random.random() is called, a new random number is generated.

In [1]:
import random

x = random.random()
y = random.random()
print(x, y)
0.9199110526377364 0.28585222076565997

Here is a little trick: we can use multiple assignment to simoultaneously assign random numbers to x and y:

In [2]:
x, y = random.random(), random.random()
print(x, y)
0.30163174845316 0.43737830722543325

Another aside: how to generate a random number between 5 and 12? The following will do the trick:

In [3]:

We are now ready to compute an approximation of π:

In [4]:
import random
N = 1000000

count = 0  #count will store the number of random points
           #that fell within the unit circle

for i in range(N):
    x, y = random.random(), random.random()
    if x**2 + y**2 < 1:
        count += 1