Skip to content

Instantly share code, notes, and snippets.

@christianscott
Last active April 30, 2018 00:37
Show Gist options
  • Save christianscott/d52d1e3b252580a81b09dec38d1bddc8 to your computer and use it in GitHub Desktop.
Save christianscott/d52d1e3b252580a81b09dec38d1bddc8 to your computer and use it in GitHub Desktop.
Covariance and Correlation in Javascript
function sum(xs) {
return xs.reduce((total, x) => total + x, 0)
}
function mean(xs) {
return sum(xs) / xs.length
}
function zip(xs, ys) {
return range(xs.length)
.reduce((arr, i) => [...arr, [xs[i], ys[i]]], [])
}
function range(start, end) {
if (end == null) {
end = start
start = 0
}
return new Array(end - start).fill().map((_, i) => i + start)
}
function stdev(xs) {
const xhat = mean(xs)
const squareDistances = xs.map(x => Math.pow(x - xhat, 2))
return Math.sqrt(sum(squareDistances) / (xs.length - 1))
}
function covariance(xs, ys) {
const xhat = mean(xs)
const yhat = mean(ys)
const total = sum(zip(xs, ys).map(([x, y]) => (x - xhat) * (y - yhat)))
return total / (xs.length - 1)
}
function correlation(xs, ys) {
return covariance(xs, ys) / (stdev(xs) * stdev(ys))
}
const xs = [1, 2, 3, 4, 5]
console.log(stdev(xs)) // 1.5811388300841898
const ys = [1, 2, 3, 4, 5]
console.log(covariance(xs, ys)) // 2.5
console.log(correlation(xs, ys)) // 0.9999999999999998
function rand(size) {
return range(size).map(() => Math.random() * size)
}
console.log(correlation(rand(100), rand(100))) // (very small +ve/-ve number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment