从阵列中获取中位数

时间:2014-10-07 20:31:45

标签: java arrays median

我想从我的数组中获取中位数长度。我使用以下代码,但我收到错误。我不知道为什么会出现这些错误。

int middleSlot = list.length/2;
    list[middleSlot];

2 个答案:

答案 0 :(得分:0)

Apache Commons Math会这样做。

http://commons.apache.org/proper/commons-math/userguide/stat.html#a1.3_Frequency_distributions

OR: Mean, Median, Mode, Range - Java

  

使用方式为:double answer = getMean(list);

<强> getMean()

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

<强> getMedian()

This method is going on the assumption that the passed array is already sorted (i.e. {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];
    }
}

<强>获取模式()

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 :(得分:0)

要将元素放在中间,您可能需要执行类似

的操作
int middleSlot = list.size()/2;
int counter =0 ;
TypeOfList middleElement=null;
for(TypeOfList eachElement: list.values) {
   if(counter == middleSlot) {
       middleElement= eachElement; break;
   }
   counter++;
}