Last active
September 4, 2015 18:05
-
-
Save scvalex/363012 to your computer and use it in GitHub Desktop.
Calculate PI probabilistically
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
#!/usr/bin/python | |
from __future__ import print_function | |
import math, random | |
acErr = 1e-5 | |
def inCircle(x, y): | |
"""inCircle(x, y) iff (x, y) is in the circle of radius 1 centered at | |
origin""" | |
return (math.sqrt(x**2 + y**2) - 1.0) <= acErr | |
def piGen(): | |
"""Generates increasingly accurate values for PI""" | |
S_circle, S_square = 0.0, 0.0 | |
while True: | |
x, y = random.random(), random.random() | |
S_circle += (1 if inCircle(x, y) else 0) | |
S_square += 1 | |
yield (4*S_circle/S_square) | |
def run_pi(): | |
random.seed() | |
print("Pi is 0.00000", end="") | |
i = 0 | |
for p in piGen(): | |
i += 1 | |
if i % 25 == 0: | |
print("\rPi is %1.5f" % p, end="") | |
if __name__ == "__main__": | |
run_pi() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment