{ "metadata": { "name": "9932_05_02" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Chapter 5, example 2\n", "====================\n", "\n", "Here we show how to parallelize a simple Monte-Carlo simulation for estimating pi." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def sample(n):\n", " return (rand(n) ** 2 + rand(n) ** 2 <= 1).sum()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pi is approximately equal to four times the ratio of points within that quarter of disc." ] }, { "cell_type": "code", "collapsed": false, "input": [ "n = 1000000.\n", "4 * sample(n) / n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 2, "text": [ "3.1425920000000001" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we create a parallel client and import the `rand` function on all engines." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.parallel import Client\n", "rc = Client()\n", "v = rc[:]\n", "with v.sync_imports():\n", " from numpy.random import rand" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "importing rand from numpy.random on engine(s)\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "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)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "4 * sum(v.map_sync(sample, [n] * len(v))) / (n * len(v))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 4, "text": [ "3.1406360000000002" ] } ], "prompt_number": 4 } ], "metadata": {} } ] }