Created
September 9, 2012 21:03
-
-
Save rodrigosetti/3687294 to your computer and use it in GitHub Desktop.
Pi Approximating by Monte Carlo method
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
# | |
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: http://en.wikipedia.org/wiki/Pi#Number_theory_and_Riemann_zeta_function