Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created July 11, 2023 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanbsd/7851a1a6bb5b99da89e18fb56bef640e to your computer and use it in GitHub Desktop.
Save romanbsd/7851a1a6bb5b99da89e18fb56bef640e to your computer and use it in GitHub Desktop.
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