How to calculate the median of an array?

后端 未结 14 1716
北海茫月
北海茫月 2020-12-05 06:10

I\'m trying to calculate the total, mean and median of an array thats populated by input received by a textfield. I\'ve managed to work out the total and the mean, I just ca

14条回答
  •  一向
    一向 (楼主)
    2020-12-05 06:52

    If you want to use any external library here is Apache commons math library using you can calculate the Median.
    For more methods and use take look at the API documentation

    import org.apache.commons.math3.*;
    .....
    ......
    ........
    //calculate median
    public double getMedian(double[] values){
     Median median = new Median();
     double medianValue = median.evaluate(values);
     return medianValue;
    }
    .......
    
    • For more on evaluate method AbstractUnivariateStatistic#evaluate

    Update

    Calculate in program

    Generally, median is calculated using the following two formulas given here

    If n is odd then Median (M) = value of ((n + 1)/2)th item term.
    If n is even then Median (M) = value of [((n)/2)th item term + ((n)/2 + 1)th item term ]/2

    In your program you have numArray, first you need to sort array using Arrays#sort

    Arrays.sort(numArray);
    int middle = numArray.length/2;
    int medianValue = 0; //declare variable 
    if (numArray.length%2 == 1) 
        medianValue = numArray[middle];
    else
       medianValue = (numArray[middle-1] + numArray[middle]) / 2;
    

提交回复
热议问题