Skip to content

Instantly share code, notes, and snippets.

@proegssilb
Created March 17, 2017 23:40
Show Gist options
  • Save proegssilb/0d7d0c37465391d577d31755b29d585f to your computer and use it in GitHub Desktop.
Save proegssilb/0d7d0c37465391d577d31755b29d585f to your computer and use it in GitHub Desktop.
A quick python function that can approximate pi "quickly" using the method outlined in https://www.youtube.com/watch?v=RZBhSi_PwHU
import gmpy2 as g
def approxPi(randomState, numTrials=5000, randbits=1024, prec=200):
"""Compute one approximation of pi using pairs of random numbers."""
with g.local_context(g.get_context()) as ctx:
ctx.precision = prec
coprime = g.mpz(0)
for i in range(numTrials):
a = g.mpz_urandomb(randomState, randbits)+1
b = g.mpz_urandomb(randomState, randbits)+1
if g.gcd(a, b) == 1:
coprime = coprime + 1
probabilityCoprime = g.mpfr(coprime)/numTrials
return g.sqrt(6/probabilityCoprime)
rs = g.random_state()
[approxPi(rs, numTrials=50000, prec=80) for i in range(10)]
"""
In my very brief experimentation, 50k trials are required with numbers in range
0 to 2*1024-1 before you reliably get 3.13 or 3.14 out. With that many trials,
Python bogs down. I'm sure there's a way to speed this up, and I'm sure I don't
know it readily, given the logic involved.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment