Lines 33
##### Keywords
mpi (4) PyMPI (1)
##### Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users

# PyMPI based Monte Carlo simulation for computing PI 0

 In Brief A snippet for computing Pi to a given precision using a Monte Carlo simulation under PyMPI.... more
 Language Python
# 's
` 1""" 2This example computes PI to certain precision using  34 processors and a monte carlo simulation. 4""" 5import random 6import mpi 7def computePi(nsamples): 8    rank, size = mpi.rank, mpi.size 9    oldpi, pi, mypi = 0.0,0.0,0.010    11    done = False12    while(not done):13        inside = 014        for i in xrange(nsamples):15            x = random.random()16            y = random.random()17            if ((x*x)+(y*y)<1):18                inside+=119        20        oldpi = pi21        mypi = (inside * 1.0)/nsamples22        pi =  (4.0 / mpi.size) * mpi.allreduce(mypi, mpi.SUM) 23        24        delta = abs(pi - oldpi)25        if(mpi.rank==0):26            print "pi:",pi," - delta:",delta27        if(delta < 0.00001):28            done = True29    return pi3031if __name__=="__main__":32    pi = computePi(10000)33    if(mpi.rank==0):34        print "Computed value of pi on",mpi.size,"processors is",pi`

A snippet for computing Pi to a given precision using a Monte Carlo simulation under PyMPI.

See http://en.wikipedia.org/wiki/Monte_Carlo_method for a decent overview of what MC is all about.