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 II

pi1.py
1import random
2 
3inside = 0
4nsamples = 120000
5 
6for i in range(nsamples):
7    x = random.random();
8    y = random.random();
9    if (x*x)+(y*y)<1:
10        inside += 1
11 
12pi = (4.* inside)/nsamples
13print "Computed value of pi is",pi
$ python ./pi1.py
Computed value of pi is 3.1449

The above program shows us how to calculate pi using random numbers. Possibly it is not the fastest and most efficient method, but this procedure is similar to Monte Carlo methods that are used in quantum chromodynamics calculations, heat shields, etc. and so it is representative of types of calculations performed on super computers.

In principle, the larger the value of nsamples that we use, the greater our accuracy will be in computing pi. This calculation could easily be run on several computers and the results averaged for higher accuracy in less time.