Skip to content

Instantly share code, notes, and snippets.

@Gerjo
Created January 26, 2014 12:45
Show Gist options
  • Select an option

  • Save Gerjo/8632194 to your computer and use it in GitHub Desktop.

Select an option

Save Gerjo/8632194 to your computer and use it in GitHub Desktop.
LeastSquaresLinearRegression: function(data, getter) {
// Assign a default trivial case getter:
if( ! getter) {
getter = function(row) {
return row;
};
}
var xy = 0;
var x = 0, xsq = 0;
var y = 0;
var n = 0;
data.forEach(function(pair) {
pair = getter(pair, n);
xsq += Math.pow(pair[0], 2);
x += pair[0];
y += pair[1];
xy += pair[0] * pair[1];
++n;
});
var b1 = (xy - x * y / n) / (xsq - Math.pow(x, 2) / n);
var b0 = (y - b1 * x) / n;
return [b0, b1];
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment