8.6. Calculating Simple Univariate Statistics
Problem
You need to calculate univariate statistics such as mean, median, variance, minimum and maximum.
Solution
Use Commons
Math’s
StatUtils
to calculate simple univariate
statistics. The following example uses StatUtils
to calculate simple statistics for a double[]
:
import org.apache.commons.math.stat.StatUtils; double[] values = new double[] { 2.3, 5.4, 6.2, 7.3, 23.3 }; System.out.println( "min: " + StatUtils.min( values ) ); System.out.println( "max: " + StatUtils.max( values ) ); System.out.println( "mean: " + StatUtils.mean( values ) ); System.out.println( "product: " + StatUtils.product( values ) ); System.out.println( "sum: " + StatUtils.sum( values ) ); System.out.println( "variance: " + StatUtils.variance( values ) );
This code executes and prints a few simple statistics to the console, as follows:
min: 2.3 max: 23.3 mean: 8.9 product: 13097.61036 sum: 44.5 variance: 68.25500000000001
Discussion
StatUtils
delegates these calculations to functors
in the
org.apache.commons.math.stat.univariate.moment
,
org.apache.commons.math.stat.univariate.rank
, and
org.apache.commons.math.stat.univariate.summary
packages. The following example uses the individual classes from
these packages to recreate the previous example, and it adds some
measures not available in StatUtil
:
import org.apache.commons.math.stat.univariate.moment.*; import org.apache.commons.math.stat.univariate.rank.*; import org.apache.commons.math.stat.univariate.summary.*; ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.