Created
March 23, 2017 22:57
-
-
Save Sneppys/0b01dc14e5d3f3ffb2ed0ebbd385e118 to your computer and use it in GitHub Desktop.
Approximates Pi using random number generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
from random import randrange | |
# check if two numbers are coprime (share no common factors other than 1) | |
def is_coprime(m, n): | |
for i in range(2, int(sqrt(min(m, n))) + 1): | |
if (m % i == 0 and n % i == 0): | |
return False | |
return True | |
# approximate pi using coprime probability | |
def approximate(total_coprime, total_rolls): | |
# probability ~= 6 / 2pi, pi ~= sqrt(6.0 / probability) | |
return sqrt(6.0 / (float(total_coprime) / float(total_rolls))) | |
# run a trial of max_rolls with a max random number amount of number_max | |
# will generate sets of 2 random numbers and check if they are coprime | |
# returns the experimental value of pi | |
def run_trial(max_rolls, number_max): | |
total = 0 | |
for count in range(max_rolls): | |
if is_coprime(randrange(1, number_max), randrange(1, number_max)): | |
total += 1 | |
return approximate(total, max_rolls) | |
print(run_trial(100000, 100000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment