Skip to content

Instantly share code, notes, and snippets.

Last active Sep 4, 2015
What would you like to do?
Calculate PI probabilistically
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
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():
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__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment