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
- r2 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_xx-sum_x*sum_x)*(n*sum_yy-sum_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!
Related posts:



2 Responses
Free Javascript Codes
14|Apr|2010very cool & good tips, thank you very much for sharing. But it’s better if you have a demo
Sergi
24|Mar|2011Many many many thanks, Trent!!!!
You save me a lot of time ;)
Cheers,
SERGI