Skip to content

Instantly share code, notes, and snippets.

Created Mar 14, 2017
What would you like to do?
Generate Pi from checking if two random numbers are coprime.
from math import sqrt
from random import randint
from math import gcd
from fractions import gcd
ITERATIONS = 1000000
MAX_INT = 1000000000
total = 0
for i in range(ITERATIONS):
a, b = randint(1, MAX_INT), randint(1, MAX_INT)
total += gcd(a, b) == 1
print(sqrt(6.0 * ITERATIONS / total))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment