Skip to content

Instantly share code, notes, and snippets.

@eebmagic
Created June 4, 2024 17:07
Show Gist options
  • Save eebmagic/33dde9916f0c04404b42888393458af3 to your computer and use it in GitHub Desktop.
Save eebmagic/33dde9916f0c04404b42888393458af3 to your computer and use it in GitHub Desktop.
Approximates pi by generating N random points and then counting how many are in a cirle (have a distance < 1 from the origin). Then uses the ratio of points inside the circle to the total number of points to approximate.
import random
import math
def genPoints(N):
points = []
for i in range(N):
points.append((random.random(), random.random()))
return points
def countInCircle(points):
inside = 0
for point in points:
x, y = point
dist = math.sqrt(x**2 + y**2)
if dist < 1:
inside += 1
return inside
N = 1_000_000
points = genPoints(N)
print(f'with {N:,} points')
ins = countInCircle(points)
approx = 4 * ins / N
print(f'\n inside: {ins:,}')
print(f'\napproximation of pi: {approx}')
error = math.pi - approx
print(f'\n error: {error}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment