Java Median median(double[] x)

Here you can find the source of median(double[] x)

Description

Returns the median of this array

License

Open Source License

Parameter

Parameter Description
x array of type <tt>double</tt>

Declaration

public static double median(double[] x) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

public class Main {
    /**//from   ww w .jav  a 2 s  .co m
     * Returns the median of this array
     * @param x array of type <tt>double</tt>
     * @return
     */
    public static double median(double[] x) {
        if (x.length == 1) {
            return x[0];
        }

        double[] y = new double[x.length];
        System.arraycopy(x, 0, y, 0, x.length);
        Arrays.sort(y);
        int n = x.length;
        double m = ((double) n) / 2.0;
        if (Math.floor(m) == m) {
            n = n / 2;
            return (y[n] + y[n - 1]) / 2.0;
        } else {
            n = (n - 1) / 2;
            return y[n];
        }
    }

    /**
     * Returns the median of this array
     * @param x array of type <tt>double</tt>
     * @return
     */
    public static float median(float[] x) {
        if (x.length == 1) {
            return x[0];
        }

        float[] y = new float[x.length];
        System.arraycopy(x, 0, y, 0, x.length);
        Arrays.sort(y);
        int n = x.length;
        float m = ((float) n) / 2.0f;
        if (Math.floor(m) == m) {
            n = n / 2;
            return (y[n] + y[n - 1]) / 2.0f;
        } else {
            n = (n - 1) / 2;
            return y[n];
        }
    }
}

Related

  1. median(double[] v)
  2. median(double[] vals)
  3. median(double[] values)
  4. median(double[] x)
  5. median(double[] x)
  6. median(double[][] values)
  7. median(final ArrayList values)
  8. median(final double... in)
  9. median(final double... values)