Monday, March 26, 2007

Monte Carlo Calculation of Pi

Program

class MonteCarlo {
    public static void main(String[] args) {
        double x, y;
        int hits = 0, limit = Integer.MAX_VALUE;

        for (int i = 0; i < limit; i++) {
            x = Math.random();
            y = Math.random();
            if (x * x + y * y <= 1) hits++;
        }

        System.out.println(4.0 * hits / limit);
        System.out.println(Math.PI);
    }
}

Output

Be prepared to wait for a while. (The program ran for 7 minutes and 48 seconds on my 1.86 GHz computer.)

[user]$ javac MonteCarlo.java
[user]$ java MonteCarlo
3.141600906449184
3.141592653589793

Discussion

The approximation Pi = 3.14166 was first obtained by Claudius Ptolemy (c. 150 AD) (O'Connor & Robertson 2001).

For a somewhat more accurate calculation of Pi, see: Computing Pi using BigDecimal.

Resources

No comments: