Skip to content

Instantly share code, notes, and snippets.

@scvalex
Last active September 4, 2015 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scvalex/363012 to your computer and use it in GitHub Desktop.
Save scvalex/363012 to your computer and use it in GitHub Desktop.
Calculate PI probabilistically
#!/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