Last active
November 20, 2020 21:00
-
-
Save edoakes/832d326f7ce06b274350b79ea3db5c53 to your computer and use it in GitHub Desktop.
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
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