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 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.13736666667

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.

LSU Homepage