Created
July 21, 2011 23:07
-
-
Save ohneda/1098455 to your computer and use it in GitHub Desktop.
StandardDeviation Category for groovy, inspired by Advanced Rails
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
import static java.lang.Math.* | |
import static java.math.RoundingMode.CEILING | |
class StandardDeviationCategory { | |
static Double mean(Collection list) { | |
list.with{ | |
scale(sum() / size()) | |
} | |
} | |
static Double stdev(Collection list){ | |
scale(sqrt(list.collect{ num -> pow(num - list.mean(),2) }.sum() / (list.size() -1))) | |
} | |
static String confidenceInterval(Collection list) { | |
list.with{ | |
confidenceInterval(list, mean(), 2*stdev()) | |
} | |
} | |
static String confidenceInterval(Double mean, Double squireStdev) { | |
"${scale(mean - squireStdev)}..${scale(mean + squireStdev)}" | |
} | |
static String stat(Collection list){ | |
list.with{ | |
def mean = mean() | |
def stdev = stdev() | |
"mean: ${mean} " + | |
"standard deviation: ${stdev} " + | |
"confidence interval: ${confidenceInterval(mean, 2*stdev)}" | |
} | |
} | |
static Double scale(BigDecimal value){ | |
value.setScale(3, CEILING) | |
} | |
} |
I'm wondering why you subtract 1 from list.size() in the std dev formula but not for mean.
I'm wondering why you subtract 1 from list.size() in the std dev formula but not for mean.
Just in case anyone else stumbles across this and is wondering, the reason is that is the definition of the standard deviation: https://en.wikipedia.org/wiki/Standard_deviation#Basic_examples
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
just a little suggestion - line 13 has list.mean() inside the closure, this will get called each iteration of the loop. Calculate it outside the closure and use that value. much faster