-
-
Save simonhayward/bddec80023c0f12d0df7ef04ac6ae671 to your computer and use it in GitHub Desktop.
monte-carlo-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 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