Question : Calculating linear regression by Java code as done in Microsoft Excel

Hi,

My goal is to calculate a linear resgression in Java code as done in Microsoft Excel functions:

SLOPE() and INTERCEPT().
I've developed the following code in Java using the Apache commons Math library:(recommended by this site for handling statisctics and available in : http://commons.apache.org/math/download_math.cgi)

        // The (...) mark is for some double data provided in the program.
        SimpleRegression regression = new SimpleRegression();
        for (int idx = 0; idx < 50; ++idx) {
            double stockReturn = ...;
            double marketReturn = ...;
            regression.addData(stockReturn, marketReturn);
        }
        intercept = regression.getIntercept();
        slope = regression.getSlope();


        However, putting all the stockReturn data in cells A1-A50 and all the marketReturn data in cells B1-B50 in an Excel sheet and then calculating in the sheet:
 SLOPE(A1:A50, B1:B50)
 INTERCEPT(A1:A50, B1:B50)

Gives other result than what was provided by the Java code.

Can you please explain what is done wrong here?

Thanks a lot!



Answer : Calculating linear regression by Java code as done in Microsoft Excel

The regression of X on Y and the regression of Y on X are different procedures.  Your Excel code is treating A1:A50 as the criterion (Y axis) and B1:B50 as the predictor (X axis).  Your Java code is treating stockReturn as X and marketReturn as Y.  Is this what you intended?

In other words, these should produce the same answer if stockReturn is in B1:B50 and marketReturn is in A1:A50.  If that's not true, you will need to reverse one of them.
Random Solutions  
 
programming4us programming4us