Created
July 11, 2023 13:57
-
-
Save romanbsd/7851a1a6bb5b99da89e18fb56bef640e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.math3.stat.regression.SimpleRegression; | |
import java.util.List; | |
public class LinearRegressionCalculator { | |
/** | |
* Calculates the slope and intercept of the line of best fit using simple linear regression. | |
* | |
* @param data A List<Double> object that represents the 'y' values of the data points. | |
* @return A double array of size 2 where the first element is the slope and the second element is the intercept. | |
*/ | |
public double[] calculateLinearRegression(List<Double> data) { | |
SimpleRegression regression = new SimpleRegression(); | |
// Add data to the regression model | |
for (int i = 0; i < data.size(); i++) { | |
regression.addData((double) i, data.get(i)); | |
} | |
double[] result = new double[2]; | |
result[0] = regression.getSlope(); // slope | |
result[1] = regression.getIntercept(); // intercept | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment