Chapter 5, example 2

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.


In [1]:
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.


In [2]:
n = 1000000.
4 * sample(n) / n


Out[2]:
3.1425920000000001

Now, we create a parallel client and import the rand function on all engines.


In [3]:
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).


In [4]:
4 * sum(v.map_sync(sample, [n] * len(v))) / (n * len(v))


Out[4]:
3.1406360000000002