Skip to content

Instantly share code, notes, and snippets.

@simonhayward
Last active November 9, 2022 20:14
Show Gist options
  • Save simonhayward/bddec80023c0f12d0df7ef04ac6ae671 to your computer and use it in GitHub Desktop.
Save simonhayward/bddec80023c0f12d0df7ef04ac6ae671 to your computer and use it in GitHub Desktop.
monte-carlo-pi
from math import sqrt
import random
points, inside, radius = 50_000, 0, 1
for point in range(points):
# Generate random x and y coordinate
rand_x = random.random()
rand_y = random.random()
# For the point (x,y) in a quadrant of a circle the
# lengths x and y become the legs of a right triangle
# whose hypotenuse is less than 1 if inside the circle.
hypotenuse = sqrt(rand_x ** 2 + rand_y ** 2)
if hypotenuse < radius:
inside += 1
approx = 4 * inside / points
print("Pi Approx:\t{}".format(approx))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment