Skip to content

Instantly share code, notes, and snippets.

@belljustin
Created April 12, 2017 22:24
Show Gist options
  • Select an option

  • Save belljustin/2d38175a1de9db0fe023947b1164a900 to your computer and use it in GitHub Desktop.

Select an option

Save belljustin/2d38175a1de9db0fe023947b1164a900 to your computer and use it in GitHub Desktop.
Approximation of pi using a Monte Carlo method
from random import uniform
import sys
def approx_pi(n):
in_circle = 0
for i in range(0, n):
x = uniform(-1, 1)
y = uniform(-1, 1)
if x**2 + y**2 <= 1:
in_circle += 1
return 4*in_circle/n
if __name__ == "__main__":
n = 1000
if len(sys.argv) > 1:
n = int(sys.argv[1])
print(approx_pi(n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment