R or Python Use Monte Carlo simulation to estimate pi Draw a
R or Python
Use Monte Carlo simulation to estimate pi. Draw a one by one square and draw a circle in it. Choose 54 points with a quasi random uniform sequence on the 1x1 sqaure and measure if they are in the circle or not.
How do we do that? Divide 1x1 square into 9 sub squares (1/3 x 1/3 each) and randomly pick 6 points for each sub square and measure if they are in the circle or not
Solution
Following is the required python code
import random;
def estimatePiForMe():
    #circle inside square is of radius 1/2
    #assuming circle and square are centered at origin
    #any point (x,y) is in circle, if it satisfies x^x + y*y < 1/4
    limits = [ [-1.0/2,-1.0/2 + 1.0/3], [-1.0/2+1.0/3, -1.0/2+ 2.0/3], [-1.0/2 + 2.0/3 , 1.0/2 ] ];
    xlimitsForSubsquares= [];
    ylimitsForSubsquares= [];  
    for i in range(3):
        xlimitsForSubsquares.extend(limits);
    for i in range(len(limits)):
        for j in range(3):
            add = [ limits[ len(limits)-1-i ][1] , limits[ len(limits)-1-i ][0] ];
            ylimitsForSubsquares.append( add );
   
    #got 9 subsquares
    incircle= 0;
    for ss in range(9):
        for rpoint in range(6):
            xval = random.random()* 1.0/3 + xlimitsForSubsquares[ss][0];
            yval = random.random()* 1.0/3 + xlimitsForSubsquares[ss][1];
            if (xval*xval + yval*yval) < 1.0/4:
                incircle= incircle + 1;
print (4*incircle*1.0)/54;
 estimatePiForMe();

