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 II

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

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.