Monday, March 24, 2014

Monte Carlo Simulation- Python

1:  '''  
2:  Program to compute the value of PI and to compute   
3:  the hit rate on the odd segments of a square  
4:  using Monte Carlo Simulation  
5:  Created on Mar 24, 2014  
6:  @author: Mridul J Kurup  
7:  '''  
8:  import random, sys  
9:  # method to compute the value of PI using monte carlo simulation  
10:  def MonteCarloSimulation(datasize):  
11:    datasize+=datasize # incrementing for end value  
12:    hitsWithinCircle=0  
13:    for i in range(datasize):  
14:      x=random.random()  
15:      y=random.random()   
16:      if x*x+y*y <= 1 :  
17:        hitsWithinCircle+=1  
18:    print("PI is : ",(4*hitsWithinCircle/datasize))    
19:  # method to compute the hit rate on a square  
20:  # divided into four parts.With part 2 and 3 half the size of 1 or 4.  
21:  # objective is to see the hit rate on the odd number regions  
22:  # As per the diagram the hit rate should be around 62.5%  
23:  def AdvancedMonteCarloSimulation(datasize):  
24:      datasize+=datasize # incrementing for end value  
25:      hitsInOdd=0  
26:      hitsInEven=0  
27:      for i in range(datasize):  
28:        x=random.random()*2  
29:        y=random.random()*2   
30:        # region of 1  
31:        if (x>0 and x<=1 and y>0 and y<=2):  
32:          hitsInOdd+=1  
33:        # region of 3  
34:        elif ((x>1 and x<=2) and (y>1 and y<=2) and (x*y <=2.25)):  
35:          hitsInOdd+=1  
36:        else:  
37:          hitsInEven+=1  
38:      print("The probability of the dart falling in odd region is : ",  
39:         round((hitsInOdd/datasize),4))  
40:      print("The probability of the dart falling in even region is : ",  
41:         round((hitsInEven/datasize),4))  
42:  '''   
43:  Function invocations  
44:  '''  
45:  # MonteCarloSimulation(int(eval(input("Enter the number of data points: "))))   
46:  # Throwing darts  
47:  MIN_RANGE=1  
48:  MAX_RANGE=100000  
49:  sentinel=True  
50:  while sentinel:  
51:    datasize=int(eval(input("Enter the no of simulations ({0}-{1}): ".  
52:                format(MIN_RANGE,MAX_RANGE))))  
53:    if (datasize<MIN_RANGE or datasize>MAX_RANGE):  
54:      print("Please enter data within range")  
55:      break  
56:    else:  
57:      AdvancedMonteCarloSimulation(datasize)  

No comments:

Post a Comment