Compute Linear Regressions in Javascript
By trent on 06 Apr in Javascript, Programming
Its very seldom, but now and then you have to go back to those old math equations from college and compute some nice graphs, or solve a few complex formulas. Linear Regressions aren’t completely foreign territory, they are used more often than you realize. I’ve put together a nice function which computes slope, intercept, and r squared in javascript (its not dependent on a framework). If you’re curious of what the equations for these functions look like you can peak at their corresponding Excel functions here:
 Intercept resembles Excel’s intercept(y,x) function
 Slope resembles Excel’s linest(y,x) function
 r^{2} resembles Excel’s rsq(y,x) function
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_xxsum_x*sum_x)*(n*sum_yysum_y*sum_y)),2);
return lr;
}
To use this you just need to pass it two arrays, known_y's and known_x's, so this is what you might pass:
var known_y = [1, 2, 3, 4];
var known_x = [5.2, 5.7, 5.0, 4.2];
var lr = linearRregression(known_y, known_x);
// now you have:
// lr.slope
// lr.intercept
// lr.r2
Simple as that! Hope this helps someone out!
4 Responses

Many many many thanks, Trent!!!!
You save me a lot of time ;)Cheers,
SERGI 
Brook Monroe  Mar 10, 2012
It becomes even more useful if you add
lr['fn'] = function (x) { return this.slope * x + this.intercept; };
That allows computation without extra code outside the object:
linResult = linearRegression(yData,xData);
y = linResult.fn(x);

ivan  Nov 01, 2012
Thanks a lot mate.
Would be cool to show a demo on a canvas in HTML5!
very cool & good tips, thank you very much for sharing. But it’s better if you have a demo