Calculation of Pi Using the Monte Carlo Method

by Eve Andersson

     

Home : Pi : One Calculation


The "Monte Carlo Method" is a method of solving problems using statistics. Given the probability, P, that an event will occur in certain conditions, a computer can be used to generate those conditions repeatedly. The number of times the event occurs divided by the number of times the conditions are generated should be approximately equal to P.

How this program works:

If a circle of radius R is inscribed inside a square with side length 2R, then the area of the circle will be pi*R^2 and the area of the square will be (2R)^2. So the ratio of the area of the circle to the area of the square will be pi/4.

This means that, if you pick N points at random inside the square, approximately N*pi/4 of those points should fall inside the circle.

This program picks points at random inside the square. It then checks to see if the point is inside the circle (it knows it's inside the circle if x^2 + y^2 < R^2, where x and y are the coordinates of the point and R is the radius of the circle). The program keeps track of how many points it's picked so far (N) and how many of those points fell inside the circle (M).

Pi is then approximated as follows:


     4*M
pi = ---
      N

Although the Monte Carlo Method is often useful for solving problems in physics and mathematics which cannot be solved by analytical means, it is a rather slow method of calculating pi. To calculate each significant digit there will have to be about 10 times as many trials as to calculate the preceding significant digit.

Great Gift!
Los Boludos
Made with original vintage vacuum tubes!




Eve Andersson (eve@eveandersson.com)

Comments

Regarin the program

Hi eveander This is suresh here, doin my master in computers in ASU .As i'm a graduate student, actully we had a topic on monte carlo (pi calculation ).when i had gone through ur site i got stuff regardin this topic i'm interested in.I would like to know the complete procedure and program code inorder to understand myself clearly.I would be greatful to u and thanks for consider my above request.

Regards suresh

-- Suresh Babu Gajjela


Re: Regarin the program

I wonder if Suresh is looking for something like this.

#!/usr/bin/env python

import random
import math

count_inside = 0
for count in range(0, 10000):
    d = math.hypot(random.random(), random.random())
    if d < 1: count_inside += 1
count += 1
print 4.0 * count_inside / count


-- Larry Hosken

more digits

Wow, someone sent me some mail about the example. She wrote:

Thank You very much for it! But I would like to please Your help. Could You tell please, what is nesessery to add to this programm for to get Pi colculations in such view 3.******** (i mean in your programm there are 4 numbers after point, but I need 8 numbers).

First, the unhelpful literal answer: To specify that you want to view 8 digits of the number, you can use a formatted string. That is, instead of something like

print 4.0 * M / N

...you can say something like

print '%0.8f' % (4.0 * M / N)

However, when you try this, you will see it is not so useful: our result is an integer divided by 10000. Thus, the last few digits are always zero. This leads to the temptation to use a longer loop to get a more precise answer. But on my wimpy computer, using a longer loop leads to a too-long run time. And raises questions about how good my random number generator is. And when should I switch over to arbitrary-precision numbers? Oh, now my head hurts.

-- Larry Hosken


Magic Numbers

Hi,

I would like to point to the fact that this particular method works especially well when you make 14 pairs of random numbers. It works very well if you generate 452 numbers.

Using 14 pairs of random cooridante pairs you can get:3.1428571428571

Using 452 you can get as close to Pi as 3.141592920354

Probably you can work out why. ;)

I used Lua to generate these numbers, and the script is:

x = 0

y=14

for i = 1, y

do

a=math.random()

b=math.random()

if (a^2+b^2<1 ) then x=x+1 end

end

print(4*x/y)

I think you can get a generally better approximation using something like this:

S = 0

n=100

for i = 1, n

do

x=math.random()

y=(1-x^2)^0.5

S=S+y

end

T=4*S/n

print(T)

-- Szilard Bokros


Practical demonstration

The San Francisco Exploratorium - possibly the coolest kids museum on the planet - has a large poker-chip-tossing machine on display for kids to calculate Pi. On my last visit there a crowd of children - not even nerd children (sorry Eve, I'm stereotyping here...) - were all standing around watching it.

-- Aidan Merritt

Old Method

This method, was known as "The method of the French Lieutenant" or "The method of generating PI casting stones in a Pond".

MARIO



-- MARIO GIOIA


Pi - my way

Hi Eve - just found you. Love your work. I calculate Pi this way: A quarter of a circle with a radius of 2 has: a) an area of Pi b) a circumference of Pi

I simply iterate triangles until I reach the accuracy of the computer & language. Here is MS word basic output using calculating area:

Max accuracy reached at iteration 28 Calculated Pi => 3.14159265358979 Iteration => 28 No of triangles => 268,435,455 Pi => 3.14159265358979323846264338327950288419716939937510... (for reference) This is end of Loop

Regards Richard Robinson

-- Richard Robinson


Hi Eve,

Here is another python program to calculate pi. It uses the PIL module to make a PNG showing the circle inscribed into the square.

Thanks!

#!/usr/bin/env python

from random import random
from math import hypot
from PIL import Image
from PIL import ImageDraw

TRIALS=10**6
XMAX=500
YMAX=500

def main():
    inside = 0
    img = Image.new('RGB', (XMAX, YMAX), "white")
    draw = ImageDraw.Draw(img)
    for i in xrange(TRIALS):
        x = random()
        y = random()
        if hypot(x, y) < 1:
            inside +=1
            draw.point((int(x*XMAX), int(y*YMAX)), fill="red")
    img.save('pi.png')
    print 'I think pi is: ', 4.0 * inside / TRIALS

if __name__ == '__main__':
    main()

Image: pi.png

-- Dennis Watson

Add a comment