Skip to content

Instantly share code, notes, and snippets.

@FredrikMeyer
Created May 7, 2024 07:09
Show Gist options
  • Save FredrikMeyer/1099aa6791e272d85b65cd33a53899a6 to your computer and use it in GitHub Desktop.
Save FredrikMeyer/1099aa6791e272d85b65cd33a53899a6 to your computer and use it in GitHub Desktop.
Estimate Pi in Python
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