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:


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:

  1. Better Javascript Date Add and Diff
  2. Javascript Ordering Object: Order Your Hash
  3. Javascript RegExp Match – Named Captures
  4. Looping Through Dates with Javascript
  5. Object Inject – Insert Item into Javascript Hash