import random
def dist(pos1, pos2):
"""
Calculates and returns the euclidian distance between two
points on a plane. pos1 and pos2 are in the form (x, y)
"""
x1, y1 = pos1
x2, y2 = pos2
distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
return distance
def estimate_pi(trials):
"""
Estimates the value of pi using a monte carlo approach
trials: the number of steps/iterations to run the simulation for
"""
hits = 0
for i in xrange(trials):
x = random.random() # random float in range [0, 1]
y = random.random()
d = dist((0.5, 0.5), (x, y))
if d < 0.5:
hits += 1
pi_estimate = 4 * hits/float(trials)
return pi_estimate
print estimate_pi(100)