Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StandardDeviation Category for groovy, inspired by Advanced Rails
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)
}
}
@pjlarson

This comment has been minimized.

Copy link

commented Aug 10, 2012

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

@beechovsky

This comment has been minimized.

Copy link

commented Oct 3, 2018

I'm wondering why you subtract 1 from list.size() in the std dev formula but not for mean.

@ewhite

This comment has been minimized.

Copy link

commented Nov 14, 2018

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
You can’t perform that action at this time.