Last active
October 11, 2015 23:28
-
-
Save softprops/3936429 to your computer and use it in GitHub Desktop.
standard deviation
This file contains 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
val xs = List(1, 2, 3, 4, 5) | |
val μ = mean(xs) | |
val σ = stddev(xs, μ) |
This file contains 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
// 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) | |
} | |
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
Mean should read: