Skip to content

Instantly share code, notes, and snippets.

@jhuttner
Created January 25, 2012 20:48
Show Gist options
  • Select an option

  • Save jhuttner/1678631 to your computer and use it in GitHub Desktop.

Select an option

Save jhuttner/1678631 to your computer and use it in GitHub Desktop.
def inside_circle(p1, p2):
# Return true if p1,p2 is contained within the unit cirle
return 0.5 > (((0.5 - p1) ** 2 + (0.5 - p2) ** 2) ** 0.5)
def appx_pi():
inside = 0
total = 0
while True:
p1 = random.random()
p2 = random.random()
if (inside_circle(p1, p2)):
inside += 1
total += 1
# inside / total = (PI * r**2) / (4 * r**2)
# inside / total = PI / 4
# 4 * inside / total = PI
if not total % 100000:
print 'appx of pi is', 4 * ((1.0 * inside) / total)
appx_pi()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment