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

 2

1----
. |
. |
.|
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 $\frac{1}{4}\pi ×{1}^{2}=\frac{1}{4}\pi$$\frac{1}{4}\pi\times 1^2 = \frac{1}{4}\pi$, and the unit square has area 1, so about $\frac{1}{4}\pi$$\frac{1}{4}\pi$ 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 $\pi$$\pi$.

To test whether the point $\left(x,y\right)$$(x, y)$ is within the unit circle, we test whether ${x}^{2}+{y}^{2}<1$$x^2+y^2<1$ (since points inside the unit circle all are less than 1 unit away from the origin, so that ${x}^{2}+{y}^{2}<1$$x^2+y^2<1$.

A small preliminary note on generating random numbers¶

We can use random.random() to generate random numbers in the interval $\left[0,1\right)$$[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]:
5+7*random.random()

Out[3]:
9.681080775786686

We are now ready to compute an approximation of $\pi$$\pi$:

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

print(4*count/N)

3.14254