均值、中位数、众数、范围 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mean, Median, Mode, Range - Java
提问by Dennis
Is there a math library that has the methods getMean()
, getMedian()
, getMode()
, and getRange()
?
是否有有方法的数学库getMean()
,getMedian()
,getMode()
,和getRange()
?
回答by fireshadow52
I'm guessing you mean the math mean, etc. I'm not sure about that, but you can always create the methods yourself!
我猜你的意思是数学平均值等。我不确定,但你总是可以自己创建方法!
getMean()
getMean()
public double getMean(double[] numberList) {
double total;
for (double d: numberList) {
total += d;
}
return total / (numberList.length);
}
getMedian()
getMedian()
This method is going on the assumption that the passed array is already sorted (i.e. {1,2,3,...}).
该方法假设传递的数组已经排序(即{1,2,3,...})。
public double getMedian(double[] numberList) {
int factor = numberList.length - 1;
double[] first = new double[(double) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numbersList[i];
}
for (int i = numberList.length; i > last.length; i--) {
last[i] = numbersList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i]) middleNumbers[i] = numberList[i];
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return middleNumbers[0];
}
}
getMode()
getMode()
public double getMode(double[] numberList) {
HashMap<Double,Double> freqs = new HashMap<Double,Double>();
for (double d: numberList) {
Double freq = freqs.get(d);
freqs.put(d, (freq == null ? 1 : freq + 1));
}
double mode = 0;
double maxFreq = 0;
for (Map.Entry<Double,Doubler> entry : freqs.entrySet()) {
double freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return mode;
}
getRange()
getRange()
public double getRange(double[] numberList) {
double initMin = numberList[0];
double initMax = numberList[0];
for (int i = 1; i <= numberList.length; i++) {
if (numberList[i] < initMin) initMin = numberList[i];
if (numberList[i] > initMax) initMax = numberList[i];
}
return initMax - initMin;
}
回答by duffymo
Apache Commons Math will do it.
Apache Commons Math 会做到这一点。
http://commons.apache.org/math/userguide/stat.html#a1.3_Frequency_distributions
http://commons.apache.org/math/userguide/stat.html#a1.3_Frequency_distributions