Last active
April 9, 2017 21:37
-
-
Save davidjmemmett/21cbf9c79b601b569a55ad67ec00b6c6 to your computer and use it in GitHub Desktop.
Using standupmaths logic, estimating pi. See https://www.youtube.com/watch?v=RZBhSi_PwHU for more information
This file contains 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
import random | |
import decimal | |
from fractions import gcd | |
decimal.getcontext().prec = 10 | |
class PiCalculator: | |
def __init__(self): | |
self.highest_number = 1000000000000000000000000000000000000000 | |
def calculate(self): | |
coprimes = 0 | |
iteration = 0 | |
total = 0.0 | |
while True: | |
iteration += 1 | |
a = random.randint(1, self.highest_number) | |
b = random.randint(1, self.highest_number) | |
if gcd(a, b) == 1: | |
coprimes += 1 | |
probability = coprimes / (iteration * 1.0) | |
if probability == 0: | |
continue | |
pi_est = decimal.Decimal(6.0 / probability).sqrt() | |
total += float(pi_est) | |
average_pi = total / iteration | |
# print 'est: %0.10f' % pi_est | |
print 'ave: %0.10f' % average_pi | |
if __name__ == '__main__': | |
a = PiCalculator() | |
a.calculate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment