Suppose we did not know the value of π and we wanted to estimate its value using Monte Carlo methods. One practical approach is to draw a square sides equal to a=2, with its diagonal opposite corners extending from the coordinates origin (−1,−1) to (1,1). Now we try to simulate uniform random points from inside of this square by generating uniform random points along the X and Y axes, i.e., by generating two random uniform numbers (x,y) from the range [−1,1].
The generated random point P has the coordinate (x,y), so we can calculate its distance from the coordinate origin. Now, suppose we also draw a unit-radius (r=1) inside of this square with its center at the origin (0,0). The ratio of the area of this circle, SC to the area of the square enclosing it, SS is,
SCSS=πr2a2=14πThis is because the area of the square with sides a=2 is just 4. Therefore, if we can somehow measure the area of the circle SC, then we can use the following equation, to get an estimate of π,
π=4SCTo obtain, SC, we are going to throw random points in the square, just as described above, and then find the fraction of points, f=nC/ntotal, that fall inside this circle. This fraction is related to the area of the circle and square by the following equation,
f=nCntotal=SCSSTherefore, one can obtain an estimate of π using this fraction,
π≈4nCntotalNow, write a script that takes in the number of points to be simulated, and then calculates an approximate value for π based on the Monte Carlo algorithm described above. Write a second function that plot the estimate of π versus the number of points stimulated, like the following,
