Skip to content

Instantly share code, notes, and snippets.

@edoakes
Last active November 20, 2020 21:00
Show Gist options
  • Save edoakes/832d326f7ce06b274350b79ea3db5c53 to your computer and use it in GitHub Desktop.
Save edoakes/832d326f7ce06b274350b79ea3db5c53 to your computer and use it in GitHub Desktop.
import math
import random
import time
from multiprocessing.pool import Pool
NUM_SAMPLES = 100000000
NUM_PROCESSES = 8
def take_sample(index):
# Generate random x and y coordinates in [-1, 1].
x, y = random.uniform(-1, 1), random.uniform(-1, 1)
# Check if the random point falls within the unit circle.
if math.hypot(x, y) <= 1:
return 1
else:
return 0
if __name__ == "__main__":
pool = Pool(processes=NUM_PROCESSES)
num_inside = 0
for result in pool.imap_unordered(take_sample, range(NUM_SAMPLES), chunksize=1000):
num_inside += result
print("pi ~= {}".format((4*num_inside)/NUM_SAMPLES))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment