从一系列频率中获得中位数?

时间:2014-05-12 07:26:52

标签: java arrays math

我有一个数组,例如在array[1]中将包含很多次,其中一个数字列在数字列表中,同样array[2]将会有很多两个数字。

这是我到目前为止所尝试的

    int tot = 0;
    for(int i=0; i<array.length; i++){
        tot += array[i];
    }
    int mid = tot/2;
    int med = array[mid];
    return med; 

这不起作用,我觉得还有很多我没做过的计算。 任何指导表示赞赏。 谢谢!

3 个答案:

答案 0 :(得分:2)

这里的问题是你需要找到你看到“中间”的索引:

int tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
}
int mid = tot/2;
int med = 0;
tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
    if(tot >= mid) { 
        med = i; 
        break; 
    }
}

return med;

<强>更新 正如Ajay Reddy在评论中所述,上面的代码只适用于数组长度不均匀的情况。对于均匀长度,有一个上部和下部中位数,其平均值是实际中位数。如果你真的想要那取决于你之后用中位数做的事情(如果它需要实际发生使用上面的代码,它会找到较低的中位数)。

int tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
}
float mid = tot/2;
int upper_med = 0;
int lower_med = 0;
tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
    if(i > 0 && array[i-1] > 0) {
        lower_med = i;
    }
    if(tot >= mid) { 
        upper_med = i; 
        break; 
    }
}

return array.length % 2 == 0 ? (float)(upper_med + lower_med)/2 : lower_med; // cast to float or not according to your requirements

答案 1 :(得分:0)

来自维基百科的Quting ... http://en.wikipedia.org/wiki/Median

通过将所有观察值从最低值排列到最高值并选择中间值(例如,{3,3,5,9,11}的中值为5),可以找到有限数字列表的中位数。如果有偶数个观察值,则没有单个中间值;然后通常将中位数定义为两个中间值的平均值({3,5,7,9}的中位数为(5 + 7)/ 2 = 6),[...]。

答案 2 :(得分:0)

您想要找到具有总频率中点的初始数组的索引。

我会计算滚动频率总数,然后检查滚动频率>,这是第一个大于中点的滚动频率。像这样:

public static void main(final String[] args) {
    /* Number   Frequency
     *      0           5
     *      1           6
     *      2           8
     *      3           1
     *      4           2
     *      5           3
     *      6           6
     *      7           9
     *      8           5
     *      9           7
     * 
     * Total = 52
     *                       Midpoint(s)
     *                          **
     * 0000011111122222222344555666666777777777888889999999
     * 
     * Median = 6
     */
    final int[] frequencies = {5,6,8,1,2,3,6,9,5,7};
    final int[] rollingFrequencies = new int[frequencies.length];

    rollingFrequencies[0] = frequencies[0];
    for (int i = 1; i < rollingFrequencies.length; i++) {
        rollingFrequencies[i] = frequencies[i] + rollingFrequencies[i-1];
    }

    //At this point, rollingFrequencies is: [5, 11, 19, 20, 22, 25, 31, 40, 45, 52]
    final int total = rollingFrequencies[rollingFrequencies.length - 1]; //The final rollingFreq will be the total.
    final int mid = total / 2;

    for (int i = 0; i < rollingFrequencies.length; i++) {
        if( rollingFrequencies[i] > mid ) {
            System.out.println( i );
            return;
        }
    }
}
相关问题