Instantly share code, notes, and snippets.

# ohneda/StandardDeviationCategory.groovy Created Jul 21, 2011

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 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 commented Oct 3, 2018

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

### ewhite commented Nov 14, 2018 • edited

 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