OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { public double calculateRSquared() throws MathIllegalArgumentException { return 1 - calculateResidualSumOfSquares() / calculateTotalSumOfSquares(); } OLSMultipleLinearRegression();  OLSMultipleLinearRegression(final double threshold); void newSampleData(double[] y, double[][] x); @Override void newSampleData(double[] data, int nobs, int nvars); RealMatrix calculateHat(); double calculateTotalSumOfSquares(); double calculateResidualSumOfSquares(); double calculateRSquared(); double calculateAdjustedRSquared();  }
@Test public void testPerfectFit() { double[] betaHat = regression.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{ 11.0, 1.0 / 2.0, 2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0, 5.0 / 6.0 }, 1e-14); double[] residuals = regression.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{0d,0d,0d,0d,0d,0d}, 1e-14); RealMatrix errors = new Array2DRowRealMatrix(regression.estimateRegressionParametersVariance(), false); final double[] s = { 1.0, -1.0 / 2.0, -1.0 / 3.0, -1.0 / 4.0, -1.0 / 5.0, -1.0 / 6.0 }; RealMatrix referenceVariance = new Array2DRowRealMatrix(s.length, s.length); referenceVariance.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(int row, int column, double value) { if (row == 0) { return s[column]; } double x = s[row] * s[column]; return (row == column) ? 2 * x : x; } }); Assert.assertEquals(0.0, errors.subtract(referenceVariance).getNorm(), 5.0e-16 * referenceVariance.getNorm()); Assert.assertEquals(1, ((OLSMultipleLinearRegression) regression).calculateRSquared(), 1E-12); }