Monday, August 02, 2010

Pi estimation with Monte Carlo Method in Python


The following page explains what Monte Carlo Method is in a very simple yet understandable way. It wasn't very difficult for me to figure it out so I guess it's not going to be too difficult for you, either!



The following is my implementation of pi estimation with Monte Carlo Method in Python.


#!/usr/bin/python

import random
import math

def get_dist ():
x = random.uniform(0,1)
y = random.uniform(0,1)
dist = math.sqrt(math.pow(x, 2) + math.pow(y, 2))
return dist


# number of hits / number of misses = ((1/4) * pi * sqrt(radius)) / sqrt(radius)
# pi = 4 * number of hits / number of misses

num_hits = 0
num_throws = 0
while 1:
num_throws += 1
# if distance from origin is <= 1, it's within the quadrant.
if (get_dist() <= 1):
num_hits += 1
pi = 4 * (num_hits / float(num_throws))
print "iteration #", num_throws, ":", pi

No comments: