Skip to content

Instantly share code, notes, and snippets.

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 purijatin/293422fe66c6f120486b578a361b7e48 to your computer and use it in GitHub Desktop.
Save purijatin/293422fe66c6f120486b578a361b7e48 to your computer and use it in GitHub Desktop.
Adding mean and variance to Scala collections.
object TraversableWithStatistics {
implicit class RichTraversable[A](collection: Traversable[A])(implicit val numeric : Numeric[A]) {
private def pow2[C](x: C)(implicit num: Numeric[C]) = math.pow(num.toDouble(x), 2)
private def sqrt[C](x: C)(implicit num: Numeric[C]) = math.sqrt(num.toDouble(x))
def mean = {
numeric.toDouble(collection.sum) / collection.size
}
def variance = {
val me: Double = mean
implicit val doubleNum = implicitly[Numeric[Double]]
collection.map(x => pow2(numeric.toDouble(x) - me)).sum / collection.size
}
def stddev = sqrt(variance)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment