[Tutor] can python calculate the digits of pi or e?,has this been done before?,how?

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Sun, 27 Aug 2000 02:47:28 -0700 (PDT)

On Fri, 25 Aug 2000, Charles Gruschow, Jr. wrote:

> can python calculate the digits of pi or e?,has this been done
> before?,how?

There's a very very cool way of calculating Pi using a "Monty Carlo"
method.  That is, we can get Pi's value through random numbers!  I haven't
tried it out myself yet, but let me see if I can remember it... Here's the
general idea --- let's call it the dart throwing method:

Ok, so you know that a circle's area is (Pi * r**2).  Draw a circle of
radius 1:

    *   *
    *   *

Our center.  Ok, now draw a square that surrounds that circle.  The square
itself has sides of length 2.

   | *** |
   |*   *|
   |*   *|
   | *** |

Our dartboard.  We can see that our picture can be divided into two
sections --- the region inside the circle, and the region outside of the

Now imagine sampling random dots on this picture.  You're throwing darts.  
Some of the darts will be in the circle, while others will fall outside
the circle.  You can write a program that simulates dart throwing, and can
count how many go inside or outside the circle.

Probablistically, the ratio between those two counts should approximate
the ratio between the _areas_ of inside and outside.  That is,

area of inside/area of outside == 
    (number of points in circle)/(number of points outside circle)

But we already know that the area inside our circle == Pi, and the area of
the outside is (area of square - circle) == 4 - Pi.

There might be an easier way to simplify the algebra, or a simpler way of
looking at this problem, so you might want to play around with it for a

I hope this gives you enough to make a Pi finding program.  You might need
to throw a lot of darts to get accuracy out of this thing, but you should
get a reasonable approximation this way.  The whrandom module, which has
functions to get random numbers, should be really helpful with this.  
Here's the link to it:


If you need more help with this method, email again to tutor@python.org.  
Good luck!