Here you can find the source of median(final double... values)
double
.
Parameter | Description |
---|---|
values | an array of doubles to calculate the median of. |
public static double median(final double... values)
//package com.java2s; /*/* w w w . j a va2s .com*/ * Copyright 2007-2010 Tom Castle & Lawrence Beadle * Licensed under GNU General Public License * * This file is part of EpochX: genetic programming software for research * * EpochX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EpochX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EpochX. If not, see <http://www.gnu.org/licenses/>. * * The latest version is available from: http:/www.epochx.org */ import java.util.Arrays; public class Main { /** * Calculates and returns the median of an array of <code>double</code>. The * provided <code>values</code>argument must not be null nor an empty array. * * @param values an array of doubles to calculate the median of. * @return the median of the provided array of doubles. */ public static double median(final double... values) { if ((values != null) && (values.length != 0)) { // Sort the array. Arrays.sort(values); // Pick out the middle value. final int medianIndex = (int) Math.floor(values.length / 2); double median = values[medianIndex - 1]; // There might have been an even number - use average of 2 medians. if ((values.length % 2) == 0) { median += values[medianIndex]; median = median / 2; } return median; } else { throw new IllegalArgumentException("cannot calculate median of null or empty array of values"); } } /** * Calculates and returns the median of an array of <code>int</code>. The * provided <code>values</code>argument must not be null nor an empty array. * * @param values an array of int to calculate the median of. * @return the median of the provided array of ints. */ public static double median(final int... values) { if ((values != null) && (values.length != 0)) { // Sort the array. Arrays.sort(values); // Pick out the middle value. final int medianIndex = (int) Math.floor(values.length / 2); int median = values[medianIndex - 1]; // There might have been an even number - use average of 2 medians. if ((values.length % 2) == 0) { median += values[medianIndex]; median = median / 2; } return median; } else { throw new IllegalArgumentException("cannot calculate median of null or empty array of values"); } } }