Skip to content

Instantly share code, notes, and snippets.

Last active February 8, 2020 01:10
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Monte Carlo Pi Estimation in Python - parallel using multiprocessing.Pool
import math
import random
import time
def sample(num_samples):
num_inside = 0
for _ in range(num_samples):
x, y = random.uniform(-1, 1), random.uniform(-1, 1)
if math.hypot(x, y) <= 1:
num_inside += 1
return num_inside
def approximate_pi_parallel(num_samples):
from multiprocessing.pool import Pool
pool = Pool()
start = time.time()
num_inside = 0
sample_batch_size = 100000
for result in, [sample_batch_size for _ in range(num_samples//sample_batch_size)]):
num_inside += result
print("pi ~= {}".format((4*num_inside)/num_samples))
print("Finished in: {:.2f}s".format(time.time()-start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment