Calculating the value of pi
Now we work through a classic example - estimating the value of \(\pi\).
Imagine a square of side \(2\) with the origin \((0, 0)\) as its center and the four corners having coordinates \((1, 1), (1, -1), (-1, 1), (-1, -1)\). The area of this square is \(2\times 2 = 4\). Now imagine a circle of radius \(1\) with its center at the origin fitting perfectly inside this square. The area of the circle will be \(\pi \times \text{radius}^2 = \pi\).
To estimate \(\pi\), we randomly sample multiple points in this square & get the fraction of points inside the circle (\(x^2 + y^2 <= 1\)). The area of the circle then is \(4\) times this fraction, which gives us our estimate of \(\pi\).
After this exercise, you'll have a grasp of how to use simulation for computation.
This exercise is part of the course
Statistical Simulation in Python
Exercise instructions
- Examine the true value of \(\pi\) using
np.pi
in the console. Initializesims
to 10000 andcircle_points
to 0. - Within the
for
loop, generate a point (x & y coordinates) usingnp.random.uniform()
between -1 and 1, havingsize=2
. - Check if the point lies within the unit circle with the equation \(x^2 + y^2 <= 1\), assign to
within_circle
, and incrementcircle_points
accordingly. - Print the estimate of \(\pi\)
pi_sim
as 4 times the fraction of points that lie within the circle.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Initialize sims and circle_points
sims, circle_points = ____, ____
for i in range(sims):
# Generate the two coordinates of a point
point = ____
# if the point lies within the unit circle, increment counter
within_circle = point[0]**2 + point[1]**2 <= 1
if ____ == True:
circle_points +=1
# Estimate pi as 4 times the avg number of points in the circle.
pi_sim = ____
print("Simulated value of pi = {}".format(pi_sim))