1. How to Program, Part I
  2. How to Program, Part II
  3. How to Program, Part III
  4. How to Program, Part IV
  5. How to Program, Part V
  6. exercises
  7. pyMPI tutorial
  8. Calculating PI, Part I
  9. Calculating PI, Part II
  10. Calculating PI, Part III
  11. Poogle - Web Search
  12. Mandelbrot Sets
  13. Mandelbrot, The Code
  14. Mandelbrot, The Images
  15. Conway's Life, Part I
  16. Life Code Listing
  17. Conway's Life, Part II
  18. 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.