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