/**************************************************************** * This class performs simple linear regression. */ public class Regression { /** The y-intercept of the line. */ private double a; /** The slope of the line. */ private double b; /** The measure of fit for the line. */ private double r2; /************************************************************ * Fit a line y = a + b * x. * @param x The x coordinates. * @param y The y coordinates. * @return int Number of data points used in regression. */ public int fit (double [] x, double [] y) { int n = Math.min (x.length, y.length); int i; double nn = (double) n; double sumX = 0; double sumY = 0; double sumXX = 0; double sumYY = 0; double sumXY = 0; for (i = 0; i < n; i++) { sumX += x[i]; sumY += y[i]; sumXX += x[i] * x[i]; sumYY += y[i] * y[i]; sumXY += x[i] * y[i]; } // for double sXX = sumXX - sumX * sumX / nn; //double sYY = sumYY - sumY * sumY / nn; double sXY = sumXY - sumX * sumY / nn; b = sXY / sXX; a = (sumY - b * sumX) / nn; r2 = (sumXY * sumXY) / (sumXX * sumYY); return n; } // fit /************************************************************ * Get the intercept (a). * @return double The intercept (a). */ public double getA () { return a; } /************************************************************ * Get the slope (b). * @return double The slope (b). */ public double getB () { return b; } /************************************************************ * Get the measure of fit (r2). * @return double The slope (b). */ public double getR2 () { return r2; } /************************************************************ * Main method for testing purpose. * @param args Command-line arguments. */ public static void main (String [] args) { double x [] = { 1.0, 2.0, 3.0, 4.0 }; double y [] = { 1.9, 4.1, 6.2, 7.9 }; Regression line = new Regression (); line.fit (x, y); System.out.println ("Regression results:"); System.out.println ("a = " + line.getA ()); System.out.println ("b = " + line.getB ()); System.out.println ("r2 = " + line.getR2 ()); } // main } // Regression