Skip to content

Instantly share code, notes, and snippets.

@hernamesbarbara
Last active August 29, 2015 13:56
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 hernamesbarbara/9345446 to your computer and use it in GitHub Desktop.
Save hernamesbarbara/9345446 to your computer and use it in GitHub Desktop.
simple linear regression in javascript
var _ = require('underscore');
function simple_linear_regression (x, y) {
var sum_x = 0
, sum_y = 0
, sum_xy = 0
, sum_xx = 0
, cnt = 0
, nrow = x.length
, m = null
, b = null;
if ( x.length != y.length) {
throw new Error('x and y must be vectors of the same length\n')
}
_.each(_.range(nrow), function (i) {
sum_x += x[i]
sum_y += y[i]
sum_xx += Math.pow(x[i], 2)
sum_xy += x[i] * y[i]
});
m = (nrow*sum_xy - sum_x*sum_y) / (nrow*sum_xx - sum_x*sum_x);
b = (sum_y/nrow) - (m*sum_x)/nrow;
return [m, b]
}
x = [10.4,10.3,11.5,12.8,13.2,13.9]
y = [0.71,0.73,0.83,0.81,0.86,0.97]
fit = simple_linear_regression(x, y)
m = fit[0]
b = fit[1]
console.log(m) // 0.057002780623444764
console.log(b) // 0.13334991950827202
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment