Skip to content

Instantly share code, notes, and snippets.

@softprops
Last active October 11, 2015 23:28
Show Gist options
  • Save softprops/3936429 to your computer and use it in GitHub Desktop.
Save softprops/3936429 to your computer and use it in GitHub Desktop.
standard deviation
val xs = List(1, 2, 3, 4, 5)
val μ = mean(xs)
val σ = stddev(xs, μ)
// http://en.wikipedia.org/wiki/Standard_deviation#Basic_examples
def mean(xs: List[Int]): Double = xs match {
case Nil => 0.0
case ys => ys.reduceLeft(_ + _) / ys.size.toDouble
}
def stddev(xs: List[Int], avg: Double): Double = xs match {
case Nil => 0.0
case ys => math.sqrt((0.0 /: ys) {
(a,e) => a + math.pow(e - avg, 2.0)
} / xs.size)
}
@lossyrob
Copy link

Mean should read:

def mean(xs: List[Int]): Double = xs match {
  case Nil => 0.0
  case ys => ys.reduceLeft(_ + _) / ys.size.toDouble
}

@russel
Copy link

russel commented Jun 8, 2014

mean of Nil and List() is undefined rather than 0.0. Also stddev of Nil, List() and List(Any()) are undefined rather than 0.0. Perhaps the return type should be Option? Or Double.NaN for the "problem" cases?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment