A simple toy problem to get a handle on multiple engines is a Monte Carlo approximation of π.
Let's say we have a dartboard with a round target inscribed on a square board. If you threw darts randomly, and they land evenly distributed on the square board, how many darts would you expect to hit the target?
from __future__ import print_function
from random import random
from math import pi
def mcpi(nsamples):
s = 0
for i in range(nsamples):
x = random()
y = random()
if x*x + y*y <= 1:
s+=1
return 4.*s/nsamples
for n in [10, 100, 1000, 10000, 100000, 1000000]:
print("%8i" % n, end=' ')
for i in range(3):
print("%.5f" % mcpi(n), end=' ')
print()
10 3.60000 2.40000 2.80000 100 2.72000 3.20000 3.20000 1000 3.14800 3.10400 3.16000 10000 3.15720 3.13480 3.16320 100000 3.13800 3.14412 3.13400 1000000 3.14120 3.14144 3.14244
%timeit mcpi(1000000)
1 loops, best of 3: 426 ms per loop
It takes a lot of samples to get a good approximation. Can you write a function that will use your engines to break up the work?
def multi_mcpi(dview, nsamples):
raise NotImplementedError("you write this")
from IPython import parallel
rc = parallel.Client()
view = rc[:]
%load ../soln/mcpi.py
multi_mcpi(view, 10000000)
3.1411995999999998