Computer Science 202
Introduction to Programming

Fall 2013, The College of Saint Rose

MonteCarloPiVisual Demo

A working demo of MonteCarloPiVisual will appear below. Click inside the applet to interact with it.



MonteCarloPiVisual BlueJ Project

Click here to download a BlueJ project for MonteCarloPiVisual.


MonteCarloPiVisual Source Code

The Java source code for MonteCarloPiVisual is below. Click on a file name to download it.


MonteCarloPiVisual.java

import objectdraw.*;
import java.awt.*;
import java.util.Random;
import javax.swing.JOptionPane;

/*
 * Example MonteCarloPiVisual: a visual version of a program that can
 * compute an approximation of pi with a Monte Carlo method.
 *
 * Jim Teresco, The College of Saint Rose, CSC 202, Fall 2013
 *
 * $Id: MonteCarloPiVisual.java 2245 2013-11-06 06:54:27Z terescoj $
 */

public class MonteCarloPiVisual extends WindowController {

    private static final int CANVAS_SIZE = 500;
    
    public void begin() {
        // make sure we have a large enough canvas
        setSize(CANVAS_SIZE, CANVAS_SIZE+50);
        
        // draw a FramedOval to fill the canvas
        FramedOval target = new FramedOval(0, 0, CANVAS_SIZE, CANVAS_SIZE, canvas);
        
        // find out how many trials to use
        String response = JOptionPane.showInputDialog("How many points to use?");
        int numPoints = Integer.parseInt(response);
        
        // create our Random object to generate the positions
        Random randGen = new Random();
        
        // keep track of the number of positions inside the target
        int hits = 0;
        
        // perform our trials
        for (int trialNum = 0; trialNum < numPoints; trialNum++) {
            Location spot = new Location(CANVAS_SIZE*randGen.nextDouble(), CANVAS_SIZE*randGen.nextDouble());
            FilledOval dart = new FilledOval(spot, 2, 2, canvas);
            if (target.contains(spot)) {
                hits++;
                dart.setColor(Color.green);
            }
            else {
                dart.setColor(Color.red);
            }
        }
        
        target.sendToFront();
        
        // our pi approximation
        double apxPi = (double)hits / numPoints * 4;

        JOptionPane.showMessageDialog(null,"Our approximation of pi: " + apxPi);
    }
}