Skip to content

Instantly share code, notes, and snippets.

@danilopinotti
Last active September 13, 2022 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilopinotti/92d14a34bd9ca14a75e03d298f625b77 to your computer and use it in GitHub Desktop.
Save danilopinotti/92d14a34bd9ca14a75e03d298f625b77 to your computer and use it in GitHub Desktop.
Simulate an approximation of PI value using Python
import numpy as np
import multiprocessing as mp
import random
import math
threads = mp.cpu_count()
points = 100_000_000
def simulate_pi(points):
radius = 1
points_inside = 0
for i in range(points):
x = random.uniform(-radius, radius)
y = random.uniform(-radius, radius)
if math.sqrt(x*x + y*y) < radius:
points_inside += 1
return 4*points_inside/points
pool = mp.Pool(mp.cpu_count())
results = pool.map(simulate_pi, [round(points/threads) for i in range(threads)])
pool.close()
print(np.mean(results))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment