Binomial.java


Below is the syntax highlighted version of Binomial.java from §3.6 Case Study: Purple America.


/******************************************************************************
 *  Compilation:  javac Binomial.java
 *  Execution:    java Binomial
 *  Dependencies: Draw.java ProbStat.java LabeledSlider.java
 *
 ******************************************************************************/

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class Binomial implements ChangeListener {
    private static final int SIZE = 600;

    private Draw draw = new Draw();
    private JFrame frame = new JFrame();
    private LabeledSlider sliderN = new LabeledSlider(5, 30, 15);
    private LabeledSlider sliderP = new LabeledSlider(2, 98, 50);

    // create the frame with an empty image
    public Binomial() {
        draw.setCanvasSize(2*SIZE, SIZE);
        draw.setXscale(-5, 35);
        draw.setYscale(0, 0.35);
        draw.enableDoubleBuffering();
        draw.show();

        // a panel for the 2 sliders
        JPanel sliders = new JPanel();
        sliders.add(sliderN);
        sliders.add(sliderP);
        sliderN.addChangeListener(this);
        sliderP.addChangeListener(this);

        // add components to the frame
        JLabel canvas = draw.getJLabel();
        frame.add(canvas,  BorderLayout.CENTER);
        frame.add(sliders, BorderLayout.NORTH);

        frame.setTitle("Normal approximation to binomial distribution");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.pack();
        stateChanged(null);   // draw default binomial distribution
        frame.setVisible(true);
    }

    public void stateChanged(ChangeEvent e) {
        int N    = sliderN.getValue();
        double p = sliderP.getValue() / 100.0;
        sliderN.setLabel("N = " + N);
        sliderP.setLabel("p = " + p);

        draw.clear();

        // normal approximation
        double mu    = N * p;
        double sigma = Math.sqrt(N * (1-p) * p);
        draw.setPenColor(Color.RED);
        draw.setPenRadius(.001);
        for (double x = -5; x <= 40; x += 0.01) {
            draw.line(x, ProbStat.gaussian(mu, sigma, x), x+.01, ProbStat.gaussian(mu, sigma, x+.01));
        }

        // binomial distribution
        draw.setPenColor(Color.BLUE);
        draw.setPenRadius(.01);
        for (int k = 0; k <= N; k++) {
            draw.line(k, 0, k, ProbStat.binomial(N, p, k));
        }
        draw.show();

        frame.repaint();   // repaints sliders and canvas
    }


    // create one frame object
    public static void main(String[] args) {
        new Binomial();
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Sun Dec 11 15:43:56 EST 2022.