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\times 1^2 = \frac{1}{4}\pi$, and the unit square has area 1, so about $\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$.
To test whether the point $(x, y)$ is within the unit circle, we test whether $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$.
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.
import random
x = random.random()
y = random.random()
print(x, y)
Here is a little trick: we can use multiple assignment to simoultaneously assign random numbers to x
and y
:
x, y = random.random(), random.random()
print(x, y)
Another aside: how to generate a random number between 5 and 12? The following will do the trick:
5+7*random.random()
We are now ready to compute an approximation of $\pi$:
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)