Java Median calcMedian(final double[] values)

Here you can find the source of calcMedian(final double[] values)

Description

Returns the median value of an array of double.

License

Apache License

Parameter

Parameter Description
values a parameter

Declaration

public static double calcMedian(final double[] values) 

Method Source Code


//package com.java2s;
/*/*ww w  . j  a  va  2s  .c om*/
 * Copyright 2016 Langhammer, Tim | Earth >> Europe >> Potsdam |
 * {@literal @}<a href="mailto:tlhammer@mailbox.org" alt="email">mail</a> |
 * "Tolerance first".
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Arrays;

public class Main {
    /**
     * Returns the median value of an array of double.
     * <p/>
     * @param values
     * @return
     */
    public static double calcMedian(final double[] values) {
        if (values == null) {
            throw new IllegalArgumentException("vector values == null!");
        }
        if (values.length == 0) {
            return 0D;
        }

        double rc;

        Arrays.sort(values);

        final int dataLength = values.length;

        // even number of samples
        if (dataLength % 2 == 0) {
            //
            rc = (values[(dataLength / 2) - 1] + values[(dataLength / 2)]) / 2;

        } else {
            // odd number of sample
            rc = values[(dataLength / 2)];
        }

        return rc;
    }
}

Related

  1. calculateMedianOfArrayListInteger(List integerList)
  2. getMedian(double array[])
  3. getMedian(double[] a)
  4. getmedian(double[] vals, int nvalindex)