Skip to content

Instantly share code, notes, and snippets.

@sarpeedo
Last active March 14, 2017 06:48
Show Gist options
  • Save sarpeedo/bb4d00f69b5d5939ea5cbd3e31809d36 to your computer and use it in GitHub Desktop.
Save sarpeedo/bb4d00f69b5d5939ea5cbd3e31809d36 to your computer and use it in GitHub Desktop.
# Author: Sarp Orgul
# Description: Cute little program that will approximate the value of Pi by
# generating random numbers. This algorithm takes advantage of the fact that the
# probability of two random number being coprime is equal to 6/pi^2. Note:
# For better results try using a better random number generator.
from math import gcd
from math import sqrt
from math import pow
from random import randint
# returns true if a and b are coprime false otherwise (uses the python gcd lib
# implemented in C which allows for faster runtime)
def coprime(a, b):
return gcd(a, b) == 1
# uses randomness to approximate pi.
# n is the number of trials
# random will generate a number between 1 and maxint
def findpi(n,maxint):
numberCoprime = 0
numberTrials = n
for i in range (0,n):
if coprime(randint(1,maxint),randint(1,maxint)):
numberCoprime = numberCoprime + 1
print(sqrt((numberTrials / numberCoprime) * 6))
def main():
findpi(100000,64);
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment