Skip to content

Instantly share code, notes, and snippets.

@rodrigosetti
Created September 9, 2012 21:03
Show Gist options
  • Save rodrigosetti/3687294 to your computer and use it in GitHub Desktop.
Save rodrigosetti/3687294 to your computer and use it in GitHub Desktop.
Pi Approximating by Monte Carlo method
#
# The probability that two integers randomly chosen are primes between then
# is surprisingly related to pi, this probability value is equal to 6/pi**2.
# This was discovered by Cesaro, in 1883.
# This code uses Monte Carlo method to test 10**7 pairs of random integers between
# 1 and 10**10 to approximate numerically the value of pi.
#
from math import sqrt # square root (to calculate pi from pi**2)
from fractions import gcd # greatest common division (to test for primality between integers)
from random import randint # yields a random integer between a range
# increment this numbers to get more accurate pi approximations
TESTS = 10**7 # number of Monte Carlo tests to perform
MAX = 10**10 # size of the uniform random integer space to sample
print sqrt( 6.*TESTS /
sum(1 for n in xrange(TESTS) if
gcd(randint(1,MAX),
randint(1,MAX)) == 1))
@rodrigosetti
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment