Text Only Login to PAWS Baton Rouge, Louisiana |
LSU Homepage
HPC RESOURCES EMPLOYMENT LOG IN SITE MAP SEARCH
homeaboutprogramprojectscyberinfrastructurenewseventscontact
  1. Bootcamp Home
  2. How to Program, Part I
  3. How to Program, Part II
  4. How to Program, Part III
  5. How to Program, Part IV
  6. How to Program, Part V
  7. exercises
  8. pyMPI tutorial
  9. Calculating PI, Part I
  10. Calculating PI, Part II
  11. Calculating PI, Part III
  12. Poogle - Web Search
  13. Mandelbrot Sets
  14. Mandelbrot, The Code
  15. Mandelbrot, The Images
  16. Conway's Life, Part I
  17. Life Code Listing
  18. Conway's Life, Part II
  19. MPI Life Code Listing

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

  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.
LSU Homepage