License Public Domain
Lines 33
Keywords
mpi (4) PyMPI (1)
Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo – the intersection of pastebin, help desk, version control, and social networking Join Siafoo Now or Learn More

PyMPI based Monte Carlo simulation for computing PI Atom Feed 0

In Brief A snippet for computing Pi to a given precision using a Monte Carlo simulation under PyMPI.... more
# '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.0
10
11 done = False
12 while(not done):
13 inside = 0
14 for i in xrange(nsamples):
15 x = random.random()
16 y = random.random()
17 if ((x*x)+(y*y)<1):
18 inside+=1
19
20 oldpi = pi
21 mypi = (inside * 1.0)/nsamples
22 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:",delta
27 if(delta < 0.00001):
28 done = True
29 return pi
30
31if __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.