modula-2 home

  Home  
  Tutorial  
  Win32 API  
  Reference  
  Projects  
 

 

Monte Carlo estimation of Pi

For ISO Modula-2

By Frank Schoonjans (frank.schoonjans@medcalc.net)

 

Monte Carlo methods are methods that use random numbers and probability statistics to solve problems. A common illustration is the estimation (rather than calculation) of Pi.

Let's look at the following figure. It shows a square with one quadrant of a circle.

As we all know, the area of the square is given by r2. The area of a circle is given by r2Pi, so the quadrant's area is r2Pi/4. The ratio of the area of the square and the quadrant therefore is Pi/4.

Now suppose we pick at random a large number of points inside the square, then the ratio of total points (inside the square) divided by the number of points inside the quadrant, will give us an estimate of Pi/4.

Modula-2 program

As a random number generator, we use a module from the Numerical Analysis library of Peter Moylan.

For convenience, we choose r = 1.

We pick random coordinates x,y in the range [0..1]. If x2 + y2 is less than or equal to 1, then the point given by x,y is inside the quadrant.

Our estimate of Pi is then 4 times the number of points in the quadrant divided by the total number of random points.

MODULE EstimatePi;

FROM STextIO  IMPORT WriteString,WriteLn,ReadChar,SkipLine;
FROM SLongIO  IMPORT WriteFixed;
FROM LongMath IMPORT pi;

FROM Rand     IMPORT RANDOM;

VAR cIn,cTot,counter : CARDINAL;
    x,y,d   : LONGREAL;
    pi_est  : LONGREAL;
    ch      : CHAR;
BEGIN
    cTot:=1000000; cIn:=0;
    FOR counter:=1 TO cTot DO
        x := VAL(LONGREAL,RANDOM());
        y := VAL(LONGREAL,RANDOM());
        d := x*x+y*y;
        IF d<=1.0 THEN INC(cIn); END;
    END;
    pi_est:=4.0*VAL(LONGREAL,cIn)/VAL(LONGREAL,cTot);
    WriteString("PI by Monte Carlo simulation = ");
    WriteFixed(pi_est,5,7);
    WriteLn;
    WriteString("PI true value                = ");
    WriteFixed(pi,5,7);
    WriteLn;
    WriteLn;
    WriteString("Press Enter to continue");
    ReadChar(ch); SkipLine;
END EstimatePi.

Results

The code as shown yields the following output:

Download

The download EstimatePi.zip contains the program's source files, and Peter Moylan's slightly modified Rand module, taken from his freeware Numerical Analysis library (ISO version). We have tested these files with ADW Modula-2, Stony Brook Modula-2 and XDS modula-2.

ADW Modula-2 and Stony Brook Modula-2

  • Mark the application as a Console application: Options - Linker Options - Win32 tab - Select "Console Application"

Links

This article is largely based on The Basics of Monte Carlo Simulations.