Skip to content

Instantly share code, notes, and snippets.

@ohneda
Created July 21, 2011 23:07
Show Gist options
  • Select an option

  • Save ohneda/1098455 to your computer and use it in GitHub Desktop.

Select an option

Save ohneda/1098455 to your computer and use it in GitHub Desktop.
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

Copy link
Copy Markdown

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

Copy link
Copy Markdown

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

@ebrooks42

ebrooks42 commented Nov 14, 2018

Copy link
Copy Markdown

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