Created
March 29, 2011 02:07
-
-
Save shepting/891695 to your computer and use it in GitHub Desktop.
Finding pi by Monte Carlo sampling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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