Skip to content

Instantly share code, notes, and snippets.

@vicapow
Created February 16, 2015 19:48
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 vicapow/aa06b3eb2bd3ae26daff to your computer and use it in GitHub Desktop.
Save vicapow/aa06b3eb2bd3ae26daff to your computer and use it in GitHub Desktop.
Ordinary Least Squares
// Ordinary Least Squares
function ols(points_, pointAccessor) {
var points = points_.map(pointAccessor || function(d) { return d })
var xmean = d3.mean(points, function(d) { return d[0] })
var ymean = d3.mean(points, function(d) { return d[1] })
var bNum = points
.reduce(function(c, d) { return (d[0] - xmean) * (d[1] - ymean) + c }, 0)
var bDenom = points
.reduce(function(c, d) { return c + Math.pow(d[0] - xmean, 2) }, 0)
var b = bNum / bDenom
var a = ymean - b * xmean
return {a: a, b: b}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment