Skip to content

Instantly share code, notes, and snippets.

@bennettandrews
Created March 12, 2013 20:00
Show Gist options
  • Save bennettandrews/5146461 to your computer and use it in GitHub Desktop.
Save bennettandrews/5146461 to your computer and use it in GitHub Desktop.
/**
* The correlation between two vectors A, B is
* cov(A, B) / (stdDev(A) * stdDev(B))
*
* This is equivalent to
* [n * dotProduct(A, B) - sum(A) * sum(B)] /
* sqrt{ [n * norm(A)^2 - sum(A)^2] [n * norm(B)^2 - sum(B)^2] }
*/
def correlation(size : Double, dotProduct : Double, ratingSum : Double,
rating2Sum : Double, ratingNormSq : Double, rating2NormSq : Double) = {
val numerator = size * dotProduct - ratingSum * rating2Sum
val denominator = scala.math.sqrt(size * ratingNormSq - ratingSum * ratingSum) * scala.math.sqrt(size * rating2NormSq - rating2Sum * rating2Sum)
numerator / denominator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment