平均值,中位数,模式,范围 - Java

时间:2011-08-19 11:57:07

标签: java methods

是否有一个包含getMean()getMedian()getMode()getRange()方法的数学库?

2 个答案:

答案 0 :(得分:6)

我猜你的意思是数学意思,等等。我不确定,但你总能自己创造方法!

getMean()

public double getMean(double[] numberList) {
    double total;
    for (double d: numberList) {
        total += d;
    }
    return total / (numberList.length);
}

getMedian()

此方法假设传递的数组已经排序(即{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()

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()

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;
}       

答案 1 :(得分:5)