Pi is an important constant in math, and — as we know — it’s an irrational number, so we can’t really know the exact value of pi. But, we know that pi is nearly equal to the ratio between the length of circle’s circumference and it’s diameter. With such information, let’s dive into math and programming and try to estimate the value of pi!
The Idea
Let say we have a square which divided to 2 equal region, region A and region B.

If we randomly draw points at that square, we know that the number of points in region A is nearly equal to the number of points in region A. it’s happen because the area of region A is equal to the area of region B and we randomly locate points on the square.

In the same way, if the area of region A is 2 times the region B, then the number of points in the region A is 2 times the number of points in region B. From this observation, we can make a conclusion. The larger the area of a region, the more likely the point is to be in that region, and it means the more points in that larger region. We can state it as:
Where A is the area of the region, and N is the number of points in that region. This observation is useful because with this conclusion, we can estimate the value of pi. but, how? let say the area of the square is 2x2. Just create 2 region, region inside a circle with radius 1 and a region outside that circle.

We know that the area of a circle is . In this case, , so the area of that circle is , and the area of this square is 4. So, the area outside the circle is . From this information, we can calculate as follow:
we can set , then:
now, we need to know the value of and , where it is the number of point randomly we draw on the square. if it’s inside the circle, then it’s counted as , and if it’s outside the circle, then it’s counted as . We just need to simulate this process by drawing random points as much as we can in the square to get a better estimation of . This method called Monte Carlo Simulation. In order to automate this computational process, we will create this simulation using python.
Simulation
Try this program and see what you’ll get :
# import matplotlib.pyplot as plt
import numpy as np
from numpy import random as r
# the equation of circle :
# x**2+y**2==r**2
cir = 0
rec = 0
# running monte carlo simulation :
for i in range(0,10000000) :
x=r.rand()
y=r.rand()
if x**2+y**2 < 1 :
cir = cir + 1
else :
rec = rec + 1
x = cir/rec
pi = (4*x)/(x+1)
print("estimated value for pi : {}".format(pi))
print("the real value of pi : {}".format(np.pi))To get a better result (but with a higher computational cost), you can increase the number of loop. this is the result that i get:
