LeastSquares.java


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


/******************************************************************************
 *  Compilation:  javac LeastSquares.java
 *  Execution:    java LeastSquares
 *  Dependencies: Draw.java DrawListener.java
 *
 *  Plots the points that the user clicks, and plots the least squares
 *  line through them.
 *
 ******************************************************************************/

import java.awt.Color;

public class LeastSquares implements DrawListener {
    private int n = 0;
    private double sumx  = 0.0;                     // sum { x[i],      i = 1..n
    private double sumy  = 0.0;                     // sum { y[i],      i = 1..n
    private double sumx2 = 0.0;                     // sum { x[i]*x[i], i = 1..n
    private double sumy2 = 0.0;                     // sum { y[i]*y[i], i = 1..n
    private double sumxy = 0.0;                     // sum { x[i]*y[i], i = 1..n
    private double[] x = new double[10000];
    private double[] y = new double[10000];

    private Draw draw = new Draw();

    public LeastSquares() {
        draw.addListener(this);
        draw.clear(Color.LIGHT_GRAY);
        draw.show();
    }

    public void mousePressed(double x0, double y0) {
        x[n] = x0;
        y[n] = y0;
        sumx  += x[n];
        sumy  += y[n];
        sumx2 += x[n]*x[n];
        sumy2 += y[n]*y[n];
        sumxy += x[n]*y[n];
        n++;

        draw.clear();

        // draw the least squares line
        draw.setPenColor(Color.BLACK);
        double a = (n*sumxy - sumx*sumy) / (n*sumx2 - sumx*sumx);
        double b = (sumy - a*sumx) / n;
        draw.line(0, b, 1, a + b);

        if (n > 0 && !Double.isNaN(a)) draw.line(0, b, 1, a + b);

        // draw the points
        for (int i = 0; i < n; i++) {
            draw.setPenColor(Color.BLUE);
            draw.filledCircle(x[i], y[i], 0.005);
            draw.setPenColor(Color.GRAY);
            if (!Double.isNaN(a)) draw.line(x[i], y[i], x[i], a*x[i] + b);
        }

        draw.show();
    }

    public void keyTyped(char c) {
        draw.save("leastsquares" + c + ".png");
    }

    // test client
    public static void main(String[] args) {
        LeastSquares ls = new LeastSquares();
    }



}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:27:28 EDT 2022.