I noticed there's some code on StackOverflow that is, to put it mildly, suboptimal. I'm posting here to see if we can provide a better solution.
Here's a proposal for fixing it.
The approach is to provide a small utility class with static methods, so it can be used just like Math.method(...)
.
The standard deviation implements this formula, which applies to a sample.
The median function is taken from this answer, which is based on the reasonable assumption that the array can be sorted in memory.
import java.util.Arrays;
public class Statistics {
static public double getMean(double[] nums) {
double total = 0;
for (double value : nums) {
total += value;
}
return total / nums.length;
}
// sample version
static public double getVariance(double[] nums) {
if (nums.length <= 1) {
return 0;
}
double sum = 0;
double mean = getMean(nums);
for (double value : nums) {
sum += Math.pow(value - mean, 2);
}
return sum / (nums.length - 1); // notice the -1
}
// sample version
static public double getStdDev(double[] nums) {
return Math.sqrt(getVariance(nums));
}
static public double getMedian(double[] nums) {
Arrays.sort(nums);
if (nums.length % 2 == 0) {
return ((double) nums[nums.length / 2] + (double) nums[nums.length / 2 - 1]) / 2;
} else {
return (double) nums[nums.length / 2];
}
}
}
Is there something you would add?
Assuming this works well, it only works for double (and float) arrays.
It does not work for int arrays, nor does it work for Container
classes, although all it would require to get it to work would be a copy-paste and some minimal changes.
Could Java 8 lambdas help make the code more generic and reduce the need for copy-paste?
Feel free to comment.