Created
March 9, 2011 20:36
-
-
Save ramalho/862953 to your computer and use it in GitHub Desktop.
Calculating pi via stochastic method
This file contains hidden or 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
import sys | |
from math import sqrt | |
from random import uniform | |
TOTAL_DEFAULT = 10**6 | |
if len(sys.argv) == 2: | |
total = int(sys.argv[1]) | |
else: | |
total = TOTAL_DEFAULT | |
dentro = 0 | |
for i in xrange(total): | |
x = uniform(-1, 1) | |
y = uniform(-1, 1) | |
if sqrt((x*x)+(y*y)) <= 1: | |
dentro += 1 | |
print 'total:', total | |
print 'dentro:', dentro | |
print 'pi:', float(dentro)/total*4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment