Skip to content

Instantly share code, notes, and snippets.

@arvsrao
Last active July 28, 2023 04:53
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 arvsrao/9562034 to your computer and use it in GitHub Desktop.
Save arvsrao/9562034 to your computer and use it in GitHub Desktop.
Monte Carlo Approximation of PI
from random import uniform
"""
Monte Carlo approximation of PI
Sample run:
person@pc-1 ~/> python pi_day.py
approximation of PI: 3.1427
"""
def generatePoints():
x = uniform(-1,1)
y = uniform(-1,1)
return (x,y)
def approx_pi(N):
points = [ generatePoints() for x in range(N) ]
indisc = [ x*x + y*y < 1 for x,y in points ]
return 4 * sum(indisc)/float(N)
if __name__ == "__main__":
N = 100000
print "approximation of PI: " + str(approx_pi(N))
@arvsrao
Copy link
Author

arvsrao commented Mar 15, 2014

Happy PI Day!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment