Skip to content

Instantly share code, notes, and snippets.

@wspeirs
Created November 13, 2013 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wspeirs/7443455 to your computer and use it in GitHub Desktop.
Save wspeirs/7443455 to your computer and use it in GitHub Desktop.
Simple statistics using commons-math3
final DescriptiveStatistics descriptiveStats = new DescriptiveStatistics(); // stores values
final SummaryStatistics summaryStats = new SummaryStatistics(); // doesn't store values
final Frequency frequency = new Frequency();
// add numbers into our stats
for(int i=0; i < NUM_VALUES; ++i) {
values[i] = rng.nextInt(MAX_VALUE);
descriptiveStats.addValue(values[i]);
summaryStats.addValue(values[i]);
frequency.addValue(values[i]);
}
// print out some standard stats
System.out.println("MIN: " + summaryStats.getMin());
System.out.println("AVG: " + String.format("%.3f", summaryStats.getMean()));
System.out.println("MAX: " + summaryStats.getMax());
// get some more complex stats only offered by DescriptiveStatistics
System.out.println("90%: " + descriptiveStats.getPercentile(90));
System.out.println("MEDIAN: " + descriptiveStats.getPercentile(50));
System.out.println("SKEWNESS: " + String.format("%.4f", descriptiveStats.getSkewness()));
System.out.println("KURTOSIS: " + String.format("%.4f", descriptiveStats.getKurtosis()));
// quick and dirty stats (need a little help from Guava to convert from int[] to double[])
System.out.println("MIN: " + StatUtils.min(Doubles.toArray(Ints.asList(values))));
System.out.println("AVG: " + String.format("%.4f", StatUtils.mean(Doubles.toArray(Ints.asList(values)))));
System.out.println("MAX: " + StatUtils.max(Doubles.toArray(Ints.asList(values))));
// some stats based upon frequencies
System.out.println("NUM OF 7s: " + frequency.getCount(7));
System.out.println("CUMULATIVE FREQUENCY OF 7: " + frequency.getCumFreq(7));
System.out.println("PERCENTAGE OF 7s: " + frequency.getPct(7));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment