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. How to Program, Part VI
  7. exercises
  8. pyMPI tutorial
  9. Calculating PI, Part I
  10. Calculating PI, Part II
  11. Calculating PI, Part III
  12. Dividing Work
  13. More MPI
  14. Poogle - Web Search
  15. Mandelbrot Sets
  16. Mandelbrot, The Code
  17. Mandelbrot, The Images
  18. Mandelbrot In CUDA
  19. Conway's Life, Part I
  20. Life Code Listing
  21. Conway's Life, Part II
  22. MPI Life Code Listing

Calculating PI, Part III

pi.py
1import random
2import mpi
3 
4inside = 0
5nsamples = 120000/mpi.size
6 
7random.seed(mpi.rank)
8for i in range(nsamples):
9    x = random.random();
10    y = random.random();
11    if (x*x)+(y*y)<1:
12        inside += 1
13 
14mypi = (4.* inside)/nsamples
15if mpi.rank==0:
16   print "mypi =",mypi,"for rank",mpi.rank
17 
18pi = (1./ mpi.size) * mpi.allreduce(mypi, mpi.SUM)
19if 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.