Here we show how to parallelize a simple Monte-Carlo simulation for estimating pi.
This function counts the number of points within a quarter of disc centered at the origin, among all points randomly sampled within the unit square.
def sample(n):
return (rand(n) ** 2 + rand(n) ** 2 <= 1).sum()
Pi is approximately equal to four times the ratio of points within that quarter of disc.
n = 1000000.
4 * sample(n) / n
3.1425920000000001
Now, we create a parallel client and import the rand
function on all engines.
from IPython.parallel import Client
rc = Client()
v = rc[:]
with v.sync_imports():
from numpy.random import rand
importing rand from numpy.random on engine(s)
Finally, we execute the simulation in parallel over all engines (each engine samples n points, and there are nk points in total if there are k engines), and we combine the results (reduce operation).
4 * sum(v.map_sync(sample, [n] * len(v))) / (n * len(v))
3.1406360000000002