Skip to content

Instantly share code, notes, and snippets.

@Eunoia
Created April 23, 2020 17:41
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 Eunoia/2fa8bcab3b88527e82cfc9df12763925 to your computer and use it in GitHub Desktop.
Save Eunoia/2fa8bcab3b88527e82cfc9df12763925 to your computer and use it in GitHub Desktop.
Linear Regression javascript
//https://stackoverflow.com/questions/6195335/linear-regression-in-javascript
function linearRegression(y,x){
var lr = {};
var n = y.length;
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var sum_yy = 0;
for (var i = 0; i < y.length; i++) {
sum_x += x[i];
sum_y += y[i];
sum_xy += (x[i]*y[i]);
sum_xx += (x[i]*x[i]);
sum_yy += (y[i]*y[i]);
}
lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
lr['intercept'] = (sum_y - lr.slope * sum_x)/n;
lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);
return lr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment