Last day, Pi Day Matt Harper posted a video in which he approximated the Pi by rolling two 120-sided dice 500 times ( see video here ). Basically, for each pair of random numbers you need to check if they are mutual or not. Then the formula
pi = sqrt(6/(n_coprimes/n_cofactors))
.
His result was around 3.05, which is pretty close.
I wanted to see what happens when more rolls are made or when the range of random integers is increased. Interestingly, my program almost always gave a result of 3.05 or is close to it, regardless of how high the setting of iterations or the random range is.
Here is my program. I ran it on Python 3.6 (Win64). The random number generator that Python uses should be very good, so maybe I made a mistake in my program?
import random from math import gcd, sqrt def pi(cp, cf): return sqrt(6/(cf/cp)) # EDIT: Second error - switched numerator/denominator... coprime = 0 cofactor = 0 iterations = 1000000 for i in range(iterations): x = random.randint(0,1000000) y = random.randint(0,1000000) if gcd(x,y) > 1: cofactor += 1 else: coprime += 1 print(pi(coprime, cofactor))
python random pi
Tim pietzcker
source share