Skip to content

Instantly share code, notes, and snippets.

@shepting
Created March 29, 2011 02:07
Show Gist options
  • Save shepting/891695 to your computer and use it in GitHub Desktop.
Save shepting/891695 to your computer and use it in GitHub Desktop.
Finding pi by Monte Carlo sampling
from random import uniform
# Variables
inside = 0
outside = 0
radius = 3
total = 1000000 # Number of runs
for i in xrange(total):
x = uniform(-radius, radius)
y = uniform(-radius, radius)
if x**2 + y**2 <= radius**2:
inside += 1
else:
outside += 1
ratio = (float(inside)/total)
print "Ratio: %s" % ratio
print "Pi: %s" % (ratio*4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment