1. Learn
  2. /
  3. Courses
  4. /
  5. Statistical Simulation in Python

Exercise

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.

Instructions

100 XP
  • Examine the true value of \(\pi\) using np.pi in the console. Initialize sims to 10000 and circle_points to 0.
  • Within the for loop, generate a point (x & y coordinates) using np.random.uniform() between -1 and 1, having size=2.
  • Check if the point lies within the unit circle with the equation \(x^2 + y^2 <= 1\), assign to within_circle, and increment circle_points accordingly.
  • Print the estimate of \(\pi\) pi_sim as 4 times the fraction of points that lie within the circle.