Skip to content

Instantly share code, notes, and snippets.

@futuraprime
Created June 9, 2015 16:24
Show Gist options
  • Save futuraprime/3e55d8441c6612044e78 to your computer and use it in GitHub Desktop.
Save futuraprime/3e55d8441c6612044e78 to your computer and use it in GitHub Desktop.
Pearson Correlation
// "data" should be an array of x,y arrays
// e.g.: [[0,1],[1,2],[2,3]]
function pearsonCorrelation(data) {
var n = data.length;
var numerator = n *
data.reduce(function(memo, d) { return memo + d[0] * d[1]; }, 0) -
data.reduce(function(memo, d) { return memo + d[0]; }, 0) *
data.reduce(function(memo, d) { return memo + d[1]; }, 0);
var denominatorX = Math.sqrt(n *
data.reduce(function(memo, d) { return memo + Math.pow(d[0], 2); }, 0) -
Math.pow(data.reduce(function(memo, d) { return memo + d[0]; }, 0), 2)
);
var denominatorY = Math.sqrt(n *
data.reduce(function(memo, d) { return memo + Math.pow(d[1], 2); }, 0) -
Math.pow(data.reduce(function(memo, d) { return memo + d[1]; }, 0), 2)
);
return numerator / (denominatorX * denominatorY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment