Forked from MishaelRosenthal/TraversableWithStatistics.scala
Last active
March 15, 2017 10:03
-
-
Save purijatin/293422fe66c6f120486b578a361b7e48 to your computer and use it in GitHub Desktop.
Adding mean and variance to Scala collections.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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