Skip to content

Instantly share code, notes, and snippets.

@tikipatel
Created March 13, 2017 19:59
Show Gist options
  • Save tikipatel/8ef704e3baa81a964d844bc705e391a3 to your computer and use it in GitHub Desktop.
Save tikipatel/8ef704e3baa81a964d844bc705e391a3 to your computer and use it in GitHub Desktop.
Get an approximation of π using probabilities of coprime integers
from random import randint
import math
def gcd(x,y):
while y!= 0:
(x, y) = (y, x % y)
return x
rolls = 1000
max_int = 10000000000
coprime_count = 0
for i in range(0,rolls):
a = randint(0, max_int)
b = randint(0, max_int)
if gcd(a, b) == 1:
coprime_count += 1
probability = coprime_count / rolls
pi = math.sqrt(6/probability)
print("π approximate: ", pi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment