Skip to content

Instantly share code, notes, and snippets.

@ohneda
Created July 21, 2011 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohneda/1098455 to your computer and use it in GitHub Desktop.
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)
}
}
@beechovsky
Copy link

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

@ebrooks42
Copy link

ebrooks42 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