# Calculating PI, Part III

 pi.py 1 import random 2 import mpi 3 4 inside = 0 5 nsamples = 120000/mpi.size 6 7 random.seed(mpi.rank) 8 for i in range(nsamples): 9 x = random.random(); 10 y = random.random(); 11 if (x*x)+(y*y)<1: 12 inside += 1 13 14 mypi = (4.0 * inside)/nsamples 15 if mpi.rank==0: 16 print "mypi =",mypi,"for rank",mpi.rank 17 18 pi = (1.0 / mpi.size) * mpi.allreduce(mypi, mpi.SUM) 19 if mpi.rank==0: 20 print "Computed value of pi on",mpi.size,"processors is",pi 21 print "Using ",mpi.size*nsamples,"samples." ```\$ mpiexec -np 2 python pi.py mypi = 3.1454 for rank 0 Computed value of pi on 2 processors is 3.1417 Using  120000 samples. Running MPI ```

The above program puts a lot together and adds some new things.

The new things are

1. random.seed(mpi.rank): This initializes the random number generator, ensuring that it gives us a different sequence on each process.
2. mpi.allreduce(mpy, mpi.SUM): This provides us with a way of adding together the results obtained on all 4 processes. In essence, this program calculates pi by computing an average of the results obtained on each process individually.
 prev next