[Tutor] re: Monte Python method you suggested for pi

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Sun, 27 Aug 2000 23:10:18 -0700 (PDT)


> the last message I sent, I meant Monte Carlo not Monte Python,
> oops... :)

Actually, that name is oddly appropriate... *grin*


There's a slight bug in the program --- it has to do with the way the
tuple assignment works.  The line:

>     rsqr,r=xt**2+yt**2,sqrt(rsqr)

will compute the two values on the right hand side first, and _then_ do
the tuple assignments afterwards.  The problem is that at the time Python
computes the right hand side, 'rsqr' isn't known.  To fix this, you'll
have to do it the non-tricky way to have the same effect.


The rest of the program looks good!  I couldn't help but try my own hand
at this.  I found a way of simplifying the logic --- just compare the
ratio between the circle and the whole area.  That is,

    Pi / 4 = (# of points in circle) / (total points)

which can be restated as:

    Pi = 4 * (# of points in circle) / (total points)

Here's the program that implements this:

### pi.py  (pie pie!)
from whrandom import random
from math import sqrt

def makePoint():
    x = (random() * 2) - 1
    y = (random() * 2) - 1
    return (x,y)

def insideCircle(p):
    x, y = p
    return sqrt(x**2 + y**2) < 1

def getPi(iterations):
    count = 0
    for i in xrange(iterations):
        if insideCircle(makePoint()):
            count = count + 1
    return 4 * count / float(iterations)
###


And a few sample runs:

###
>>> getPi(10)
3.6
>>> getPi(100)
3.32
>>> getPi(1000)
3.144
>>> getPi(10000)
3.1132
>>> getPi(100000)
3.14792
>>> getPi(1000000)
# After a long long long time...
3.141808
###

So this isn't quite an efficient way of calculating Pi, but it does work.