Last active
July 28, 2023 04:53
-
-
Save arvsrao/9562034 to your computer and use it in GitHub Desktop.
Monte Carlo Approximation of PI
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
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Happy PI Day!!