Calculating PI, Part III
| file: 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 | |
| 20 | if mpi.rank==0: |
| 21 | print "Computed value of pi on",mpi.size,"processors is",pi |
| 22 | print "Using ",mpi.size*nsamples,"samples." |
> mpirun -np 4 pyMPI pi.py
mypi = 3.1496 for rank 0 Computed value of pi on 4 processors is 3.13696666667 Using 120000 samples.
|
The above program puts a lot together and adds some new things.
The new things are
- random.seed(mpi.rank): This initializes the random number generator, ensuring that it
gives us a different sequence on each process.
- 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.
|