Created
May 7, 2024 07:09
-
-
Save FredrikMeyer/1099aa6791e272d85b65cd33a53899a6 to your computer and use it in GitHub Desktop.
Estimate Pi in Python
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 random | |
N = 100_000 | |
def inside_circle(p): | |
return p[0] ** 2 + p[1] ** 2 <= 1 | |
def generate_point(): | |
return [random() * 2 - 1, random() * 2 - 1] | |
def estimate_pi(): | |
random_points = [generate_point() for _ in range(N)] | |
total_inside_circle = 0 | |
for p in random_points: | |
if inside_circle(p): | |
total_inside_circle += 1 | |
return total_inside_circle * 4.0 / N | |
if __name__ == "__main__": | |
print(estimate_pi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment