Median.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.statistics.descriptive;

  18. import java.util.Objects;
  19. import org.apache.commons.numbers.arrays.Selection;

  20. /**
  21.  * Returns the median of the available values.
  22.  *
  23.  * <p>For values of length {@code n}, let {@code k = n / 2}:
  24.  * <ul>
  25.  * <li>The result is {@code NaN} if {@code n = 0}.
  26.  * <li>The result is {@code values[k]} if {@code n} is odd.
  27.  * <li>The result is {@code (values[k - 1] + values[k]) / 2} if {@code n} is even.
  28.  * </ul>
  29.  *
  30.  * <p>This implementation respects the ordering imposed by
  31.  * {@link Double#compare(double, double)} for {@code NaN} values. If a {@code NaN} occurs
  32.  * in the selected positions in the fully sorted values then the result is {@code NaN}.
  33.  *
  34.  * <p>The {@link NaNPolicy} can be used to change the behaviour on {@code NaN} values.
  35.  *
  36.  * <p>Instances of this class are immutable and thread-safe.
  37.  *
  38.  * @see #with(NaNPolicy)
  39.  * @see <a href="https://en.wikipedia.org/wiki/Median">Median (Wikipedia)</a>
  40.  * @since 1.1
  41.  */
  42. public final class Median {
  43.     /** Default instance. */
  44.     private static final Median DEFAULT = new Median(false, NaNPolicy.INCLUDE);

  45.     /** Flag to indicate if the data should be copied. */
  46.     private final boolean copy;
  47.     /** NaN policy for floating point data. */
  48.     private final NaNPolicy nanPolicy;
  49.     /** Transformer for NaN data. */
  50.     private final NaNTransformer nanTransformer;

  51.     /**
  52.      * @param copy Flag to indicate if the data should be copied.
  53.      * @param nanPolicy NaN policy.
  54.      */
  55.     private Median(boolean copy, NaNPolicy nanPolicy) {
  56.         this.copy = copy;
  57.         this.nanPolicy = nanPolicy;
  58.         nanTransformer = NaNTransformers.createNaNTransformer(nanPolicy, copy);
  59.     }

  60.     /**
  61.      * Return a new instance with the default options.
  62.      *
  63.      * <ul>
  64.      * <li>{@linkplain #withCopy(boolean) Copy = false}
  65.      * <li>{@linkplain #with(NaNPolicy) NaN policy = include}
  66.      * </ul>
  67.      *
  68.      * <p>Note: The default options configure for processing in-place and including
  69.      * {@code NaN} values in the data. This is the most efficient mode and has the
  70.      * smallest memory consumption.
  71.      *
  72.      * @return the median implementation
  73.      * @see #withCopy(boolean)
  74.      * @see #with(NaNPolicy)
  75.      */
  76.     public static Median withDefaults() {
  77.         return DEFAULT;
  78.     }

  79.     /**
  80.      * Return an instance with the configured copy behaviour. If {@code false} then
  81.      * the input array will be modified by the call to evaluate the median; otherwise
  82.      * the computation uses a copy of the data.
  83.      *
  84.      * @param v Value.
  85.      * @return an instance
  86.      */
  87.     public Median withCopy(boolean v) {
  88.         return new Median(v, nanPolicy);
  89.     }

  90.     /**
  91.      * Return an instance with the configured {@link NaNPolicy}.
  92.      *
  93.      * <p>Note: This implementation respects the ordering imposed by
  94.      * {@link Double#compare(double, double)} for {@code NaN} values: {@code NaN} is
  95.      * considered greater than all other values, and all {@code NaN} values are equal. The
  96.      * {@link NaNPolicy} changes the computation of the statistic in the presence of
  97.      * {@code NaN} values.
  98.      *
  99.      * <ul>
  100.      * <li>{@link NaNPolicy#INCLUDE}: {@code NaN} values are moved to the end of the data;
  101.      * the size of the data <em>includes</em> the {@code NaN} values and the median will be
  102.      * {@code NaN} if any value used for median interpolation is {@code NaN}.
  103.      * <li>{@link NaNPolicy#EXCLUDE}: {@code NaN} values are moved to the end of the data;
  104.      * the size of the data <em>excludes</em> the {@code NaN} values and the median will
  105.      * never be {@code NaN} for non-zero size. If all data are {@code NaN} then the size is zero
  106.      * and the result is {@code NaN}.
  107.      * <li>{@link NaNPolicy#ERROR}: An exception is raised if the data contains {@code NaN}
  108.      * values.
  109.      * </ul>
  110.      *
  111.      * <p>Note that the result is identical for all policies if no {@code NaN} values are present.
  112.      *
  113.      * @param v Value.
  114.      * @return an instance
  115.      */
  116.     public Median with(NaNPolicy v) {
  117.         return new Median(copy, Objects.requireNonNull(v));
  118.     }

  119.     /**
  120.      * Evaluate the median.
  121.      *
  122.      * <p>Note: This method may partially sort the input values if not configured to
  123.      * {@link #withCopy(boolean) copy} the input data.
  124.      *
  125.      * @param values Values.
  126.      * @return the median
  127.      */
  128.     public double evaluate(double[] values) {
  129.         // Floating-point data handling
  130.         final int[] bounds = new int[1];
  131.         final double[] x = nanTransformer.apply(values, bounds);
  132.         final int n = bounds[0];
  133.         // Special cases
  134.         if (n <= 2) {
  135.             switch (n) {
  136.             case 2:
  137.                 // Sorting the array matches the behaviour of Quantile for n==2
  138.                 // Handle NaN and signed zeros
  139.                 if (Double.compare(x[1], x[0]) < 0) {
  140.                     final double t = x[0];
  141.                     x[0] = x[1];
  142.                     x[1] = t;
  143.                 }
  144.                 return Interpolation.mean(x[0], x[1]);
  145.             case 1:
  146.                 return x[0];
  147.             default:
  148.                 return Double.NaN;
  149.             }
  150.         }
  151.         // Median index
  152.         final int m = n >>> 1;
  153.         // Odd
  154.         if ((n & 0x1) == 1) {
  155.             Selection.select(x, 0, n, m);
  156.             return x[m];
  157.         }
  158.         // Even: require (m-1, m)
  159.         Selection.select(x, 0, n, new int[] {m - 1, m});
  160.         return Interpolation.mean(x[m - 1], x[m]);
  161.     }

  162.     /**
  163.      * Evaluate the median.
  164.      *
  165.      * <p>Note: This method may partially sort the input values if not configured to
  166.      * {@link #withCopy(boolean) copy} the input data.
  167.      *
  168.      * @param values Values.
  169.      * @return the median
  170.      */
  171.     public double evaluate(int[] values) {
  172.         final int[] x = copy ? values.clone() : values;
  173.         final int n = values.length;
  174.         // Special cases
  175.         if (n <= 2) {
  176.             switch (n) {
  177.             case 2:
  178.                 // Sorting the array matches the behaviour of Quantile for n==2
  179.                 if (x[1] < x[0]) {
  180.                     final int t = x[0];
  181.                     x[0] = x[1];
  182.                     x[1] = t;
  183.                 }
  184.                 return Interpolation.mean(x[0], x[1]);
  185.             case 1:
  186.                 return x[0];
  187.             default:
  188.                 return Double.NaN;
  189.             }
  190.         }
  191.         // Median index
  192.         final int m = n >>> 1;
  193.         // Odd
  194.         if ((n & 0x1) == 1) {
  195.             Selection.select(x, 0, n, m);
  196.             return x[m];
  197.         }
  198.         // Even: require (m-1, m)
  199.         Selection.select(x, 0, n, new int[] {m - 1, m});
  200.         return Interpolation.mean(x[m - 1], x[m]);
  201.     }
  202. }