You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ah...@apache.org on 2024/06/17 07:31:39 UTC

(commons-statistics) 01/02: STATISTICS-85: Quantile implementation

This is an automated email from the ASF dual-hosted git repository.

aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-statistics.git

commit 2e3303f637dc3a94a41facd42f6b2baa0a9b1c5b
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Jan 11 17:27:40 2024 +0000

    STATISTICS-85: Quantile implementation
    
    Add Quantile implementation that uses the selection routine in the
    Numbers arrays package.
    
    Also adds a Median implementation with simplified interpolation of the
    middle pair of values for even length arrays.
---
 commons-statistics-descriptive/pom.xml             |   13 +-
 .../commons/statistics/descriptive/DoubleMath.java |  104 ++
 .../commons/statistics/descriptive/Median.java     |  169 ++++
 .../commons/statistics/descriptive/NaNPolicy.java  |   31 +
 .../statistics/descriptive/NaNTransformer.java     |   62 ++
 .../statistics/descriptive/NaNTransformers.java    |  142 +++
 .../commons/statistics/descriptive/Quantile.java   |  649 ++++++++++++
 .../statistics/descriptive/DoubleMathTest.java     |  208 ++++
 .../commons/statistics/descriptive/MedianTest.java |  138 +++
 .../descriptive/NaNTransformersTest.java           |  130 +++
 .../statistics/descriptive/QuantileTest.java       |  392 ++++++++
 commons-statistics-examples/examples-jmh/pom.xml   |   16 +
 .../jmh/descriptive/MedianPerformance.java         |  169 ++++
 .../jmh/descriptive/QuantilePerformance.java       | 1064 ++++++++++++++++++++
 .../jmh/descriptive/QuantilePerformanceTest.java   |   60 ++
 pom.xml                                            |    1 +
 src/conf/pmd/pmd-ruleset.xml                       |   16 +-
 17 files changed, 3359 insertions(+), 5 deletions(-)

diff --git a/commons-statistics-descriptive/pom.xml b/commons-statistics-descriptive/pom.xml
index 8288a6e..ecb8f81 100644
--- a/commons-statistics-descriptive/pom.xml
+++ b/commons-statistics-descriptive/pom.xml
@@ -44,6 +44,16 @@
 
     <dependencies>
 
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-numbers-core</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-numbers-arrays</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-rng-simple</artifactId>
@@ -58,7 +68,8 @@
 
         <dependency>
             <groupId>org.apache.commons</groupId>
-            <artifactId>commons-numbers-core</artifactId>
+            <artifactId>commons-math3</artifactId>
+            <scope>test</scope>
         </dependency>
 
         <!-- Required for DoubleEquivalence -->
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleMath.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleMath.java
new file mode 100644
index 0000000..579ebcb
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleMath.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Support class for double math.
+ *
+ * @since 1.1
+ */
+final class DoubleMath {
+    /** No instances. */
+    private DoubleMath() {}
+
+    /**
+     * Compute the arithmetic mean of the two values taking care to avoid overflow.
+     *
+     * @param x Value.
+     * @param y Value.
+     * @return the mean
+     */
+    static double mean(double x, double y) {
+        final double v = x + y;
+        if (Double.isFinite(v)) {
+            return v * 0.5;
+        }
+        // Note: Using this by default can be incorrect on sub-normal numbers
+        return x * 0.5 + y * 0.5;
+    }
+
+    /**
+     * Linear interpolation between sorted values {@code a <= b} using the
+     * interpolant {@code t} taking care to avoid overflow.
+     *
+     * <pre>
+     * value = a + t * (b - a)
+     * </pre>
+     *
+     * <p>Note
+     *
+     * <p>This function has the same properties of as the C++ function <a
+     * href="https://en.cppreference.com/w/cpp/numeric/lerp">std::lerp</a> for
+     * {@code t in (0, 1)} and {@code b >= a}. It is not a full implementation as it
+     * removes explicit checks for {@code t==0} and {@code t==1} and does not support
+     * extrapolation as the usage is intended for interpolation of sorted values.
+     * The function is monotonic and avoids overflow for finite {@code a} and {@code b}.
+     *
+     * <p>Interpolation between equal signed infinity arguments will return {@code a}.
+     * Alternative implementations may return {@code NaN} for this case. Thus this method
+     * interprets infinity values as equivalent and avoids interpolation.
+     *
+     * @param a Min value.
+     * @param b Max value.
+     * @param t Interpolant in (0, 1).
+     * @return the value
+     */
+    static double interpolate(double a, double b, double t) {
+        // Linear interpolation adapted from:
+        // P0811R2: Well-behaved interpolation for numbers and pointers
+        // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0811r2.html
+        // https://en.cppreference.com/w/cpp/numeric/lerp
+
+        // Notes:
+        // a+t*(b-a) does not in general reproduce b when t==1, and can overflow if a and b
+        // have the largest exponent and opposite signs.
+        // t*b+(1-t)*a is not monotonic in general (unless the product ab≤0).
+
+        // Exact, monotonic, bounded, determinate, and (for a=b=0) consistent:
+        // Removed check a >= 0 && b <= 0 as the arguments are assumed to be sorted.
+        if (a <= 0 && b >= 0) {
+            // Note: Does not return a for a=-0.0, b=0.0, t=0.0.
+            // This is ignored as interpolation is only used when t != 0.0.
+            return t * b + (1.0 - t) * a;
+        }
+
+        // Here a and b are on the same side of zero, and at least 1 is non-zero.
+        // Since we assume t in (0, 1) remove: if t==1 return b.
+
+        // P0811R2 assumes finite arguments so we add a case to detect same signed infinity
+        // and avoid (b - a) == NaN. This is simply handled with floating-point equivalence.
+        if (a == b) {
+            return a;
+        }
+
+        // Exact at t=0, monotonic except near t=1,
+        // bounded, determinate, and consistent:
+        // Note: switching to 'b - (1.0 - t) * (b - a)' when t > 0.5 would
+        // provide exact ends at t=0 and t=1.
+        return a + t * (b - a);
+    }
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Median.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Median.java
new file mode 100644
index 0000000..03c1869
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Median.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.descriptive;
+
+import java.util.Objects;
+import org.apache.commons.numbers.arrays.Selection;
+
+/**
+ * Returns the median of the available values.
+ *
+ * <p>For values of length {@code n}, let {@code k = n / 2}:
+ * <ul>
+ * <li>The result is {@code NaN} if {@code n = 0}.
+ * <li>The result is {@code values[k]} if {@code n} is odd.
+ * <li>The result is {@code (values[k - 1] + values[k]) / 2} if {@code n} is even.
+ * </ul>
+ *
+ * <p>This implementation respects the ordering imposed by
+ * {@link Double#compare(double, double)} for {@code NaN} values. If a {@code NaN} occurs
+ * in the selected positions in the fully sorted values then the result is {@code NaN}.
+ *
+ * <p>The {@link NaNPolicy} can be used to change the behaviour on {@code NaN} values.
+ *
+ * @see #with(NaNPolicy)
+ * @see <a href="https://en.wikipedia.org/wiki/Median">Median (Wikipedia)</a>
+ * @since 1.1
+ */
+public final class Median {
+    /** Default instance. */
+    private static final Median DEFAULT = new Median(false, NaNPolicy.INCLUDE);
+
+    /** Flag to indicate if the data should be copied. */
+    private final boolean copy;
+    /** NaN policy for floating point data. */
+    private final NaNPolicy nanPolicy;
+    /** Transformer for NaN data. */
+    private final NaNTransformer nanTransformer;
+
+    /**
+     * @param copy Flag to indicate if the data should be copied.
+     * @param nanPolicy NaN policy.
+     */
+    private Median(boolean copy, NaNPolicy nanPolicy) {
+        this.copy = copy;
+        this.nanPolicy = nanPolicy;
+        nanTransformer = NaNTransformers.createNaNTransformer(nanPolicy, copy);
+    }
+
+    /**
+     * Return a new instance with the default options.
+     *
+     * <ul>
+     * <li>{@linkplain #withCopy(boolean) Copy = false}
+     * <li>{@linkplain #with(NaNPolicy) NaN policy = include}
+     * </ul>
+     *
+     * <p>Note: The default options configure for processing in-place and including
+     * {@code NaN} values in the data. This is the most efficient mode and has the
+     * smallest memory consumption.
+     *
+     * @return the median implementation
+     * @see #withCopy(boolean)
+     * @see #with(NaNPolicy)
+     */
+    public static Median withDefaults() {
+        return DEFAULT;
+    }
+
+    /**
+     * Return an instance with the configured copy behaviour. If {@code false} then
+     * the input array will be modified by the call to evaluate the median; otherwise
+     * the computation uses a copy of the data.
+     *
+     * @param v Value.
+     * @return an instance
+     */
+    public Median withCopy(boolean v) {
+        return new Median(v, nanPolicy);
+    }
+
+    /**
+     * Return an instance with the configured {@link NaNPolicy}.
+     *
+     * <p>Note: This implementation respects the ordering imposed by
+     * {@link Double#compare(double, double)} for {@code NaN} values: {@code NaN} is
+     * considered greater than all other values, and all {@code NaN} values are equal. The
+     * {@link NaNPolicy} changes the computation of the statistic in the presence of
+     * {@code NaN} values.
+     *
+     * <ul>
+     * <li>{@link NaNPolicy#INCLUDE}: {@code NaN} values are moved to the end of the data;
+     * the size of the data <em>includes</em> the {@code NaN} values and the median will be
+     * {@code NaN} if any value used for median interpolation is {@code NaN}.
+     * <li>{@link NaNPolicy#EXCLUDE}: {@code NaN} values are moved to the end of the data;
+     * the size of the data <em>excludes</em> the {@code NaN} values and the median will
+     * never be {@code NaN} for non-zero size. If all data are {@code NaN} then the size is zero
+     * and the result is {@code NaN}.
+     * <li>{@link NaNPolicy#ERROR}: An exception is raised if the data contains {@code NaN}
+     * values.
+     * </ul>
+     *
+     * <p>Note that the result is identical for all policies if no {@code NaN} values are present.
+     *
+     * @param v Value.
+     * @return an instance
+     */
+    public Median with(NaNPolicy v) {
+        return new Median(copy, Objects.requireNonNull(v));
+    }
+
+    /**
+     * Evaluate the median.
+     *
+     * <p>Note: This method may partially sort the input values if not configured to
+     * {@link #withCopy(boolean) copy} the input data.
+     *
+     * @param values Values.
+     * @return the median
+     */
+    public double evaluate(double[] values) {
+        // Floating-point data handling
+        final int[] bounds = new int[1];
+        final double[] x = nanTransformer.apply(values, bounds);
+        final int n = bounds[0];
+        // Special cases
+        if (n <= 2) {
+            switch (n) {
+            case 2:
+                // Sort data handling NaN and signed zeros.
+                // Matches the default behaviour of Quantile using p=0.5.
+                if (Double.compare(x[1], x[0]) < 0) {
+                    final double t = x[0];
+                    x[0] = x[1];
+                    x[1] = t;
+                }
+                return DoubleMath.mean(x[0], x[1]);
+            case 1:
+                return x[0];
+            default:
+                return Double.NaN;
+            }
+        }
+        // Median index
+        final int m = n >>> 1;
+        // Odd
+        if ((n & 0x1) == 1) {
+            Selection.select(x, 0, n, m);
+            return x[m];
+        }
+        // Even: require (m-1, m)
+        Selection.select(x, 0, n, new int[] {m - 1, m});
+        return DoubleMath.mean(x[m - 1], x[m]);
+    }
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNPolicy.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNPolicy.java
new file mode 100644
index 0000000..9c12006
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNPolicy.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Defines the policy for {@link Double#NaN NaN} values found in data.
+ *
+ * @since 1.1
+ */
+public enum NaNPolicy {
+    /** NaNs are included in the data. */
+    INCLUDE,
+    /** NaNs are excluded from the data. */
+    EXCLUDE,
+    /** NaNs result in an exception. */
+    ERROR
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformer.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformer.java
new file mode 100644
index 0000000..f85a697
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformer.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Defines a transformer for {@code NaN} values in arrays.
+ *
+ * <p>This interface is not intended for a public API. It provides a consistent method
+ * to handle partial sorting of {@code double[]} data in the {@link Median} and
+ * {@link Quantile} classes.
+ *
+ * <p>The transformer allows pre-processing floating-point data before applying a sort algorithm.
+ * This is required to handle {@code NaN}.
+ *
+ * <p>Note: The {@code <} relation does not provide a total order on all double
+ * values: {@code -0.0 == 0.0} is {@code true} and a {@code NaN}
+ * value compares neither less than, greater than, nor equal to any value,
+ * even itself.
+ *
+ * <p>The {@link Double#compare(double, double)} method imposes the ordering:
+ * {@code -0.0} is treated as less than value
+ * {@code 0.0} and {@code Double.NaN} is considered greater than any
+ * other value and all {@code Double.NaN} values are considered equal.
+ *
+ * <p>This interface allows implementations to respect the behaviour of
+ * {@link Double#compare(double, double)}, or implement different behaviour.
+ *
+ * @since 1.1
+ */
+interface NaNTransformer {
+    /**
+     * Pre-process the data for partitioning.
+     *
+     * <p>This method will scan all the data and apply processing to {@code NaN} values.
+     *
+     * <p>The method will return:
+     * <ul>
+     * <li>An array to partition; this may be a copy.
+     * <li>The {@code size} of the data; this can be smaller than the input array length if
+     * the transformer is configured to exclude NaN values.
+     * </ul>
+     *
+     * @param data Data.
+     * @param bounds [size].
+     * @return pre-processed data (may be a copy)
+     */
+    double[] apply(double[] data, int[] bounds);
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformers.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformers.java
new file mode 100644
index 0000000..b0d6d18
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/NaNTransformers.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Support for creating {@link NaNTransformer} implementations.
+ *
+ * @since 1.1
+ */
+final class NaNTransformers {
+
+    /** No instances. */
+    private NaNTransformers() {}
+
+    /**
+     * Creates a {@link NaNTransformer} based on the
+     * {@code nanPolicy} and data {@code copy} policy.
+     *
+     * <p>The transformer is thread-safe.
+     *
+     * @param nanPolicy NaN policy.
+     * @param copy Set to {@code true} to use a copy of the data.
+     * @return the transformer
+     */
+    static NaNTransformer createNaNTransformer(NaNPolicy nanPolicy, boolean copy) {
+        if (nanPolicy == NaNPolicy.INCLUDE) {
+            return new IncludeNaNTransformer(copy);
+        }
+        if (nanPolicy == NaNPolicy.EXCLUDE) {
+            return new ExcludeNaNTransformer(copy);
+        }
+        // NaNPolicy.ERROR
+        return new ErrorNaNTransformer(copy);
+    }
+
+    /**
+     * A NaN transformer that optionally copies the data.
+     * No NaN processing is done as it is assumed that downstream sorting will
+     * move NaN to the end of the data.
+     */
+    private static final class IncludeNaNTransformer implements NaNTransformer {
+        /** Set to {@code true} to use a copy of the data. */
+        private final boolean copy;
+
+        /**
+         * @param copy Set to {@code true} to use a copy of the data.
+         */
+        IncludeNaNTransformer(boolean copy) {
+            this.copy = copy;
+        }
+
+        @Override
+        public double[] apply(double[] data, int[] bounds) {
+            bounds[0] = data.length;
+            if (copy) {
+                return data.clone();
+            }
+            return data;
+        }
+    }
+
+    /**
+     * A transformer that moves {@code NaN} to the upper end of the array.
+     */
+    private static final class ExcludeNaNTransformer implements NaNTransformer {
+        /** Set to {@code true} to use a copy of the data. */
+        private final boolean copy;
+
+        /**
+         * @param copy Set to {@code true} to use a copy of the data.
+         */
+        ExcludeNaNTransformer(boolean copy) {
+            this.copy = copy;
+        }
+
+        @Override
+        public double[] apply(double[] data, int[] bounds) {
+            // Optionally work on a copy
+            final double[] a = copy ? data.clone() : data;
+            // Move NaN to end
+            int end = a.length;
+            for (int i = end; --i >= 0;) {
+                final double v = a[i];
+                if (v != v) {
+                    a[i] = a[--end];
+                    a[end] = v;
+                }
+            }
+            // Set the size excluding NaN
+            bounds[0] = end;
+            return a;
+        }
+    }
+
+    /**
+     * A transformer that errors on {@code NaN}.
+     */
+    private static final class ErrorNaNTransformer implements NaNTransformer {
+        /** Set to {@code true} to use a copy of the data. */
+        private final boolean copy;
+
+        /**
+         * @param copy Set to {@code true} to use a copy of the data.
+         */
+        ErrorNaNTransformer(boolean copy) {
+            this.copy = copy;
+        }
+
+        @Override
+        public double[] apply(double[] data, int[] bounds) {
+            // Delay copy until data is checked for NaN
+            final double[] a = data;
+            // Error on NaN
+            for (int i = a.length; --i >= 0;) {
+                final double v = a[i];
+                if (v != v) {
+                    throw new IllegalArgumentException("NaN at " + i);
+                }
+            }
+            bounds[0] = a.length;
+            // No NaNs so copy the data if required
+            if (copy) {
+                return data.clone();
+            }
+            return data;
+        }
+    }
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Quantile.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Quantile.java
new file mode 100644
index 0000000..29117b9
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Quantile.java
@@ -0,0 +1,649 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.commons.statistics.descriptive;
+
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.function.IntToDoubleFunction;
+import org.apache.commons.numbers.arrays.Selection;
+
+/**
+ * Provides quantile computation.
+ *
+ * <p>For values of length {@code n}:
+ * <ul>
+ * <li>The result is {@code NaN} if {@code n = 0}.
+ * <li>The result is {@code values[0]} if {@code n = 1}.
+ * <li>Otherwise the result is computed using the {@link EstimationMethod}.
+ * </ul>
+ *
+ * <p>Computation of multiple quantiles and will handle duplicate and unordered
+ * probabilities. Passing ordered probabilities is recommended if the order is already
+ * known as this can improve efficiency; for example using uniform spacing through the
+ * array data, or to identify extreme values from the data such as {@code [0.001, 0.999]}.
+ *
+ * <p>This implementation respects the ordering imposed by
+ * {@link Double#compare(double, double)} for {@code NaN} values. If a {@code NaN} occurs
+ * in the selected positions in the fully sorted values then the result is {@code NaN}.
+ *
+ * <p>The {@link NaNPolicy} can be used to change the behaviour on {@code NaN} values.
+ *
+ * @see #with(NaNPolicy)
+ * @see <a href="http://en.wikipedia.org/wiki/Quantile">Quantile (Wikipedia)</a>
+ * @since 1.1
+ */
+public final class Quantile {
+    /** Message when the probability is not in the range {@code [0, 1]}. */
+    private static final String INVALID_PROBABILITY = "Invalid probability: ";
+    /** Message when no probabilities are provided for the varargs method. */
+    private static final String NO_PROBABILITIES_SPECIFIED = "No probabilities specified";
+    /** Message when the size is not valid. */
+    private static final String INVALID_SIZE = "Invalid size: ";
+    /** Message when the number of probabilities in a range is not valid. */
+    private static final String INVALID_NUMBER_OF_PROBABILITIES = "Invalid number of probabilities: ";
+
+    /** Default instance. Method 8 is recommended by Hyndman and Fan. */
+    private static final Quantile DEFAULT = new Quantile(false, NaNPolicy.INCLUDE, EstimationMethod.HF8);
+
+    /** Flag to indicate if the data should be copied. */
+    private final boolean copy;
+    /** NaN policy for floating point data. */
+    private final NaNPolicy nanPolicy;
+    /** Transformer for NaN data. */
+    private final NaNTransformer nanTransformer;
+    /** Estimation type used to determine the value from the quantile. */
+    private final EstimationMethod estimationType;
+
+    /**
+     * @param copy Flag to indicate if the data should be copied.
+     * @param nanPolicy NaN policy.
+     * @param estimationType Estimation type used to determine the value from the quantile.
+     */
+    private Quantile(boolean copy, NaNPolicy nanPolicy, EstimationMethod estimationType) {
+        this.copy = copy;
+        this.nanPolicy = nanPolicy;
+        this.estimationType = estimationType;
+        nanTransformer = NaNTransformers.createNaNTransformer(nanPolicy, copy);
+    }
+
+    /**
+     * Return a new instance with the default options.
+     *
+     * <ul>
+     * <li>{@linkplain #withCopy(boolean) Copy = false}
+     * <li>{@linkplain #with(NaNPolicy) NaN policy = include}
+     * <li>{@linkplain #with(EstimationMethod) Estimation method = HF8}
+     * </ul>
+     *
+     * <p>Note: The default options configure for processing in-place and including
+     * {@code NaN} values in the data. This is the most efficient mode and has the
+     * smallest memory consumption.
+     *
+     * @return the quantile implementation
+     * @see #withCopy(boolean)
+     * @see #with(NaNPolicy)
+     * @see #with(EstimationMethod)
+     */
+    public static Quantile withDefaults() {
+        return DEFAULT;
+    }
+
+    /**
+     * Return an instance with the configured copy behaviour. If {@code false} then
+     * the input array will be modified by the call to evaluate the quantiles; otherwise
+     * the computation uses a copy of the data.
+     *
+     * @param v Value.
+     * @return an instance
+     */
+    public Quantile withCopy(boolean v) {
+        return new Quantile(v, nanPolicy, estimationType);
+    }
+
+    /**
+     * Return an instance with the configured {@link NaNPolicy}.
+     *
+     * <p>Note: This implementation respects the ordering imposed by
+     * {@link Double#compare(double, double)} for {@code NaN} values: {@code NaN} is
+     * considered greater than all other values, and all {@code NaN} values are equal. The
+     * {@link NaNPolicy} changes the computation of the statistic in the presence of
+     * {@code NaN} values.
+     *
+     * <ul>
+     * <li>{@link NaNPolicy#INCLUDE}: {@code NaN} values are moved to the end of the data;
+     * the size of the data <em>includes</em> the {@code NaN} values and the quantile will be
+     * {@code NaN} if any value used for quantile interpolation is {@code NaN}.
+     * <li>{@link NaNPolicy#EXCLUDE}: {@code NaN} values are moved to the end of the data;
+     * the size of the data <em>excludes</em> the {@code NaN} values and the quantile will
+     * never be {@code NaN} for non-zero size. If all data are {@code NaN} then the size is zero
+     * and the result is {@code NaN}.
+     * <li>{@link NaNPolicy#ERROR}: An exception is raised if the data contains {@code NaN}
+     * values.
+     * </ul>
+     *
+     * <p>Note that the result is identical for all policies if no {@code NaN} values are present.
+     *
+     * @param v Value.
+     * @return an instance
+     */
+    public Quantile with(NaNPolicy v) {
+        return new Quantile(copy, Objects.requireNonNull(v), estimationType);
+    }
+
+    /**
+     * Return an instance with the configured {@link EstimationMethod}.
+     *
+     * @param v Value.
+     * @return an instance
+     */
+    public Quantile with(EstimationMethod v) {
+        return new Quantile(copy, nanPolicy, Objects.requireNonNull(v));
+    }
+
+    /**
+     * Generate {@code n} evenly spaced probabilities in the range {@code [0, 1]}.
+     *
+     * <pre>
+     * 1/(n + 1), 2/(n + 1), ..., n/(n + 1)
+     * </pre>
+     *
+     * @param n Number of probabilities.
+     * @return the probabilities
+     * @throws IllegalArgumentException if {@code n < 1}
+     */
+    public static double[] probabilities(int n) {
+        checkNumberOfProbabilities(n);
+        final double c1 = n + 1.0;
+        final double[] p = new double[n];
+        for (int i = 0; i < n; i++) {
+            p[i] = (i + 1.0) / c1;
+        }
+        return p;
+    }
+
+    /**
+     * Generate {@code n} evenly spaced probabilities in the range {@code [p1, p2]}.
+     *
+     * <pre>
+     * w = p2 - p1
+     * p1 + w/(n + 1), p1 + 2w/(n + 1), ..., p1 + nw/(n + 1)
+     * </pre>
+     *
+     * @param n Number of probabilities.
+     * @param p1 Lower probability.
+     * @param p2 Upper probability.
+     * @return the probabilities
+     * @throws IllegalArgumentException if {@code n < 1}; if the probabilities are not in the
+     * range {@code [0, 1]}; or {@code p2 <= p1}.
+     */
+    public static double[] probabilities(int n, double p1, double p2) {
+        checkProbability(p1);
+        checkProbability(p2);
+        if (p2 <= p1) {
+            throw new IllegalArgumentException("Invalid range: [" + p1 + ", " + p2 + "]");
+        }
+        final double[] p = probabilities(n);
+        for (int i = 0; i < n; i++) {
+            p[i] = (1 - p[i]) * p1 + p[i] * p2;
+        }
+        return p;
+    }
+
+    /**
+     * Evaluate the {@code p}-th quantile of the values.
+     *
+     * <p>Note: This method may partially sort the input values if not configured to
+     * {@link #withCopy(boolean) copy} the input data.
+     *
+     * <p><strong>Performance</strong>
+     *
+     * <p>It is not recommended to use this method for repeat calls for different quantiles
+     * within the same values. The {@link #evaluate(double[], double...)} method should be used
+     * which provides better performance.
+     *
+     * @param values Values.
+     * @param p Probability for the quantile to compute.
+     * @return the quantile
+     * @throws IllegalArgumentException if the probability {@code p} is not in the range {@code [0, 1]}
+     * @see #evaluate(double[], double...)
+     */
+    public double evaluate(double[] values, double p) {
+        checkProbability(p);
+        // Floating-point data handling
+        final int[] bounds = new int[1];
+        final double[] x = nanTransformer.apply(values, bounds);
+        final int n = bounds[0];
+        // Special cases
+        if (n <= 1) {
+            return n == 0 ? Double.NaN : x[0];
+        }
+        final double pos = estimationType.index(p, n);
+        final int i = (int) pos;
+
+        // Partition and compute
+        if (pos > i) {
+            Selection.select(x, 0, n, new int[] {i, i + 1});
+            return DoubleMath.interpolate(x[i], x[i + 1], pos - i);
+        }
+        Selection.select(x, 0, n, i);
+        return x[i];
+    }
+
+    /**
+     * Evaluate the {@code p}-th quantiles of the values.
+     *
+     * <p>Note: This method may partially sort the input values if not configured to
+     * {@link #withCopy(boolean) copy} the input data.
+     *
+     * @param values Values.
+     * @param p Probabilities for the quantiles to compute.
+     * @return the quantiles
+     * @throws IllegalArgumentException if any probability {@code p} is not in the range {@code [0, 1]};
+     * or no probabilities are specified.
+     */
+    public double[] evaluate(double[] values, double... p) {
+        checkProbabilities(p);
+        // Floating-point data handling
+        final int[] bounds = new int[1];
+        final double[] x = nanTransformer.apply(values, bounds);
+        final int n = bounds[0];
+        // Special cases
+        final double[] q = new double[p.length];
+        if (n <= 1) {
+            Arrays.fill(q, n == 0 ? Double.NaN : x[0]);
+            return q;
+        }
+
+        // Collect interpolation positions. We use the output q as storage.
+        final int[] indices = new int[p.length << 1];
+        int count = 0;
+        for (int k = 0; k < p.length; k++) {
+            final double pos = estimationType.index(p[k], n);
+            q[k] = pos;
+            final int i = (int) pos;
+            indices[count++] = i;
+            if (pos > i) {
+                // Require the next index for interpolation
+                indices[count++] = i + 1;
+            }
+        }
+
+        // Partition
+        Selection.select(x, 0, n, truncate(indices, count));
+
+        // Compute
+        for (int k = 0; k < p.length; k++) {
+            final int i = (int) q[k];
+            if (q[k] > i) {
+                q[k] = DoubleMath.interpolate(x[i], x[i + 1], q[k] - i);
+            } else {
+                q[k] = x[i];
+            }
+        }
+        return q;
+    }
+
+    /**
+     * Evaluate the {@code p}-th quantile of the values.
+     *
+     * <p>This method can be used when the values of known size are already sorted.
+     *
+     * <pre>{@code
+     * short[] x = ...
+     * Arrays.sort(x);
+     * double q = Quantile.withDefaults().evaluate(x.length, i -> x[i], 0.05);
+     * }</pre>
+     *
+     * @param n Size of the values.
+     * @param values Values function.
+     * @param p Probability for the quantile to compute.
+     * @return the quantile
+     * @throws IllegalArgumentException if {@code size < 0}; or if the probability {@code p} is
+     * not in the range {@code [0, 1]}.
+     */
+    public double evaluate(int n, IntToDoubleFunction values, double p) {
+        checkSize(n);
+        checkProbability(p);
+        // Special case
+        if (n <= 1) {
+            return n == 0 ? Double.NaN : values.applyAsDouble(0);
+        }
+        final double pos = estimationType.index(p, n);
+        final int i = (int) pos;
+        final double v1 = values.applyAsDouble(i);
+        if (pos > i) {
+            final double v2 = values.applyAsDouble(i + 1);
+            return DoubleMath.interpolate(v1, v2, pos - i);
+        }
+        return v1;
+    }
+
+    /**
+     * Evaluate the {@code p}-th quantiles of the values.
+     *
+     * <p>This method can be used when the values of known size are already sorted.
+     *
+     * <pre>{@code
+     * short[] x = ...
+     * Arrays.sort(x);
+     * double[] q = Quantile.withDefaults().evaluate(x.length, i -> x[i], 0.25, 0.5, 0.75);
+     * }</pre>
+     *
+     * @param n Size of the values.
+     * @param values Values function.
+     * @param p Probabilities for the quantiles to compute.
+     * @return the quantiles
+     * @throws IllegalArgumentException if {@code size < 0}; if any probability {@code p} is
+     * not in the range {@code [0, 1]}; or no probabilities are specified.
+     */
+    public double[] evaluate(int n, IntToDoubleFunction values, double... p) {
+        checkSize(n);
+        checkProbabilities(p);
+        // Special case
+        final double[] q = new double[p.length];
+        if (n <= 1) {
+            Arrays.fill(q, n == 0 ? Double.NaN : values.applyAsDouble(0));
+            return q;
+        }
+        for (int k = 0; k < p.length; k++) {
+            final double pos = estimationType.index(p[k], n);
+            final int i = (int) pos;
+            final double v1 = values.applyAsDouble(i);
+            if (pos > i) {
+                final double v2 = values.applyAsDouble(i + 1);
+                q[k] = DoubleMath.interpolate(v1, v2, pos - i);
+            } else {
+                q[k] = v1;
+            }
+        }
+        return q;
+    }
+
+    /**
+     * Check the probability {@code p} is in the range {@code [0, 1]}.
+     *
+     * @param p Probability for the quantile to compute.
+     * @throws IllegalArgumentException if the probability is not in the range {@code [0, 1]}
+     */
+    private static void checkProbability(double p) {
+        // Logic negation will detect NaN
+        if (!(p >= 0 && p <= 1)) {
+            throw new IllegalArgumentException(INVALID_PROBABILITY + p);
+        }
+    }
+
+    /**
+     * Check the probabilities {@code p} are in the range {@code [0, 1]}.
+     *
+     * @param p Probabilities for the quantiles to compute.
+     * @throws IllegalArgumentException if any probabilities {@code p} is not in the range {@code [0, 1]};
+     * or no probabilities are specified.
+     */
+    private static void checkProbabilities(double... p) {
+        if (p.length == 0) {
+            throw new IllegalArgumentException(NO_PROBABILITIES_SPECIFIED);
+        }
+        for (final double pp : p) {
+            checkProbability(pp);
+        }
+    }
+
+    /**
+     * Check the {@code size} is positive.
+     *
+     * @param n Size of the values.
+     * @throws IllegalArgumentException if {@code size < 0}
+     */
+    private static void checkSize(int n) {
+        if (n < 0) {
+            throw new IllegalArgumentException(INVALID_SIZE + n);
+        }
+    }
+
+    /**
+     * Check the number of probabilities {@code n} is strictly positive.
+     *
+     * @param n Number of probabilities.
+     * @throws IllegalArgumentException if {@code c < 1}
+     */
+    private static void checkNumberOfProbabilities(int n) {
+        if (n < 1) {
+            throw new IllegalArgumentException(INVALID_NUMBER_OF_PROBABILITIES + n);
+        }
+    }
+
+    /**
+     * Truncate the array {@code a} to the given {@code size}. If the array length matches
+     * the {@code size} the original array is returned.
+     *
+     * @param a Array.
+     * @param size Size.
+     * @return the array of the specified size
+     */
+    private static int[] truncate(int[] a, int size) {
+        if (size < a.length) {
+            return Arrays.copyOf(a, size);
+        }
+        return a;
+    }
+
+    /**
+     * Estimation methods for a quantile. Provides the nine quantile algorithms
+     * defined in Hyndman and Fan (1996)[1] as {@code HF1 - HF9}.
+     *
+     * <p>Samples quantiles are defined by:
+     *
+     * <p>\[ Q(p) = (1 - \gamma) x_j + \gamma x_{j+1} \]
+     *
+     * <p>where \( \frac{j-m}{n} \leq p \le \frac{j-m+1}{n} \), \( x_j \) is the \( j \)th
+     * order statistic, \( n \) is the sample size, the value of \( \gamma \) is a function
+     * of \( j = \lfloor np+m \rfloor \) and \( g = np + m - j \), and \( m \) is a constant
+     * determined by the sample quantile type.
+     *
+     * <p>Note that the real-valued position \( np + m \) is a 1-based index and
+     * \( j \in [1, n] \). If the real valued position is computed as beyond the lowest or
+     * highest values in the sample, this implementation will return the minimum or maximum
+     * observation respectively.
+     *
+     * <p>Types 1, 2, and 3 are discontinuous functions of \( p \); types 4 to 9 are continuous
+     * functions of \( p \).
+     *
+     * <p>For the continuous functions, the probability \( p_k \) is provided for the \( k \)-th order
+     * statistic in size \( n \). Samples quantiles are equivalently obtained to \( Q(p) \) by
+     * linear interpolation between points \( (p_k, x_k) \) and \( (p_{k+1}, x_{k+1}) \) for
+     * any \( p_k \leq p \leq p_{k+1} \).
+     *
+     * <ol>
+     * <li>Hyndman and Fan (1996)
+     *     <i>Sample Quantiles in Statistical Packages.</i>
+     *     The American Statistician, 50, 361-365.
+     *     <a href="https://www.jstor.org/stable/2684934">doi.org/10.2307/2684934</a>
+     * <li><a href="http://en.wikipedia.org/wiki/Quantile">Quantile (Wikipedia)</a>
+     * </ol>
+     */
+    public enum EstimationMethod {
+        /**
+         * Inverse of the empirical distribution function.
+         *
+         * <p>\( m = 0 \). \( \gamma = 0 \) if \( g = 0 \), and 1 otherwise.
+         */
+        HF1 {
+            @Override
+            double position0(double p, int n) {
+                // position = np + 0. This is 1-based so adjust to 0-based.
+                return Math.ceil(n * p) - 1;
+            }
+        },
+        /**
+         * Similar to {@link #HF1} with averaging at discontinuities.
+         *
+         * <p>\( m = 0 \). \( \gamma = 0.5 \) if \( g = 0 \), and 1 otherwise.
+         */
+        HF2 {
+            @Override
+            double position0(double p, int n) {
+                final double pos = n * p;
+                // Average at discontinuities
+                final int j = (int) pos;
+                final double g = pos - j;
+                if (g == 0) {
+                    return j - 0.5;
+                }
+                // As HF1 : ceil(j + g) - 1
+                return j;
+            }
+        },
+        /**
+         * The observation closest to \( np \). Ties are resolved to the nearest even order statistic.
+         *
+         * <p>\( m = -1/2 \). \( \gamma = 0 \) if \( g = 0 \) and \( j \) is even, and 1 otherwise.
+         */
+        HF3 {
+            @Override
+            double position0(double p, int n) {
+                // Let rint do the work for ties to even
+                return Math.rint(n * p) - 1;
+            }
+        },
+        /**
+         * Linear interpolation of the inverse of the empirical CDF.
+         *
+         * <p>\( m = 0 \). \( p_k = \frac{k}{n} \).
+         */
+        HF4 {
+            @Override
+            double position0(double p, int n) {
+                // np + 0 - 1
+                return n * p - 1;
+            }
+        },
+        /**
+         * A piecewise linear function where the knots are the values midway through the steps of
+         * the empirical CDF. Proposed by Hazen (1914) and popular amongst hydrologists.
+         *
+         * <p>\( m = 1/2 \). \( p_k = \frac{k - 1/2}{n} \).
+         */
+        HF5 {
+            @Override
+            double position0(double p, int n) {
+                // np + 0.5 - 1
+                return n * p - 0.5;
+            }
+        },
+        /**
+         * Linear interpolation of the expectations for the order statistics for the uniform
+         * distribution on [0,1]. Proposed by Weibull (1939).
+         *
+         * <p>\( m = p \). \( p_k = \frac{k}{n + 1} \).
+         *
+         * <p>This method computes the quantile as per the Apache Commons Math Percentile
+         * legacy implementation.
+         */
+        HF6 {
+            @Override
+            double position0(double p, int n) {
+                // np + p - 1
+                return (n + 1) * p - 1;
+            }
+        },
+        /**
+         * Linear interpolation of the modes for the order statistics for the uniform
+         * distribution on [0,1]. Proposed by Gumbull (1939).
+         *
+         * <p>\( m = 1 - p \). \( p_k = \frac{k - 1}{n - 1} \).
+         */
+        HF7 {
+            @Override
+            double position0(double p, int n) {
+                // np + 1-p - 1
+                return (n - 1) * p;
+            }
+        },
+        /**
+         * Linear interpolation of the approximate medians for order statistics.
+         *
+         * <p>\( m = (p + 1)/3 \). \( p_k = \frac{k - 1/3}{n + 1/3} \).
+         *
+         * <p>As per Hyndman and Fan (1996) this approach is most recommended as it provides
+         * an approximate median-unbiased estimate regardless of distribution.
+         */
+        HF8 {
+            @Override
+            double position0(double p, int n) {
+                return n * p + (p + 1) / 3 - 1;
+            }
+        },
+        /**
+         * Quantile estimates are approximately unbiased for the expected order statistics if
+         * \( x \) is normally distributed.
+         *
+         * <p>\( m = p/4 + 3/8 \). \( p_k = \frac{k - 3/8}{n + 1/4} \).
+         */
+        HF9 {
+            @Override
+            double position0(double p, int n) {
+                // np + p/4 + 3/8 - 1
+                return (n + 0.25) * p - 0.625;
+            }
+        };
+
+        /**
+         * Finds the real-valued position for calculation of the quantile.
+         *
+         * <p>Return {@code i + g} such that the quantile value from sorted data is:
+         *
+         * <p>value = data[i] + g * (data[i+1] - data[i])
+         *
+         * <p>Warning: Interpolation should not use {@code data[i+1]} unless {@code g != 0}.
+         *
+         * <p>Note: In contrast to the definition of Hyndman and Fan in the class header
+         * which uses a 1-based position, this is a zero based index. This change is for
+         * convenience when addressing array positions.
+         *
+         * @param p p<sup>th</sup> quantile.
+         * @param n Size.
+         * @return a real-valued position (0-based) into the range {@code [0, n)}
+         */
+        abstract double position0(double p, int n);
+
+        /**
+         * Finds the index {@code i} and fractional part {@code g} of a real-valued position
+         * to interpolate the quantile.
+         *
+         * <p>Return {@code i + g} such that the quantile value from sorted data is:
+         *
+         * <p>value = data[i] + g * (data[i+1] - data[i])
+         *
+         * <p>Note: Interpolation should not use {@code data[i+1]} unless {@code g != 0}.
+         *
+         * @param p p<sup>th</sup> quantile.
+         * @param n Size.
+         * @return index (in [0, n-1])
+         */
+        final double index(double p, int n) {
+            final double pos = position0(p, n);
+            // Bounds check in [0, n-1]
+            if (pos < 0) {
+                return 0;
+            }
+            if (pos > n - 1.0) {
+                return n - 1.0;
+            }
+            return pos;
+        }
+    }
+}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleMathTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleMathTest.java
new file mode 100644
index 0000000..d695bd4
--- /dev/null
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleMathTest.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.descriptive;
+
+import java.util.stream.Stream;
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Test for {@link DoubleMath}.
+ */
+class DoubleMathTest {
+    @ParameterizedTest
+    @MethodSource
+    void testMean(double x, double y, double expected) {
+        Assertions.assertEquals(expected, DoubleMath.mean(x, y));
+    }
+
+    static Stream<Arguments> testMean() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        builder.add(Arguments.of(2, 3, 2.5));
+        builder.add(Arguments.of(-4, 3, -0.5));
+        builder.add(Arguments.of(-4, 4, 0));
+        builder.add(Arguments.of(-0.0, -0.0, -0.0));
+        builder.add(Arguments.of(-Double.MAX_VALUE, Double.MAX_VALUE, 0));
+        builder.add(Arguments.of(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE));
+        builder.add(Arguments.of(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE));
+        builder.add(Arguments.of(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE));
+        builder.add(Arguments.of(-Double.MAX_VALUE, Double.MAX_VALUE, 0));
+        builder.add(Arguments.of(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
+        builder.add(Arguments.of(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY));
+        builder.add(Arguments.of(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN));
+        return builder.build();
+    }
+
+    @ParameterizedTest
+    @MethodSource
+    void testInterpolate(double a, double b, double t, double expected) {
+        Assertions.assertEquals(expected, DoubleMath.interpolate(a, b, t));
+    }
+
+    static Stream<Arguments> testInterpolate() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        // Same cases as the mean
+        builder.add(Arguments.of(2, 3, 0.5, 2.5));
+        builder.add(Arguments.of(-4, 3, 0.5, -0.5));
+        builder.add(Arguments.of(-4, 4, 0.5, 0));
+        builder.add(Arguments.of(-0.0, -0.0, 0.5, -0.0));
+        builder.add(Arguments.of(-Double.MAX_VALUE, Double.MAX_VALUE, 0.5, 0));
+        builder.add(Arguments.of(Double.MIN_VALUE, Double.MIN_VALUE, 0.5, Double.MIN_VALUE));
+        builder.add(Arguments.of(Double.MAX_VALUE, Double.MAX_VALUE, 0.5, Double.MAX_VALUE));
+        builder.add(Arguments.of(-Double.MAX_VALUE, -Double.MAX_VALUE, 0.5, -Double.MAX_VALUE));
+        builder.add(Arguments.of(-Double.MAX_VALUE, Double.MAX_VALUE, 0.5, 0));
+        builder.add(Arguments.of(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0.5, Double.POSITIVE_INFINITY));
+        builder.add(Arguments.of(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.5, Double.NEGATIVE_INFINITY));
+        builder.add(Arguments.of(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0.5, Double.NaN));
+        // Interpolation
+        builder.add(Arguments.of(1, 11, 0, 1));
+        builder.add(Arguments.of(1, 11, 0.1, 2));
+        builder.add(Arguments.of(1, 11, 0.2, 3));
+        builder.add(Arguments.of(1, 11, 0.7, 8));
+        builder.add(Arguments.of(1, 11, 1, 11));
+        // Edge case from:
+        // https://stackoverflow.com/questions/4353525/floating-point-linear-interpolation
+        // https://stackoverflow.com/a/23716956
+        builder.add(Arguments.of(0.45, 0.45, 0.81965185546875, 0.45));
+        // https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/
+        builder.add(Arguments.of(127, 127, 5.0586262771736122e-15, 127));
+        builder.add(Arguments.of(1.7, 1.7, 0.4, 1.7));
+        // t=0 for zero. This captures the current interpolation behaviour where argument 'a'
+        // is not always returned if t==0.
+        builder.add(Arguments.of(-0.0, -0.0, 0.0, -0.0));
+        builder.add(Arguments.of(-0.0, -0.0, 1.0, -0.0));
+        builder.add(Arguments.of(-0.0, 0.0, 0.0, 0.0));
+        builder.add(Arguments.of(-0.0, 0.0, 1.0, 0.0));
+        return builder.build();
+    }
+
+    @ParameterizedTest
+    @MethodSource
+    void testInterpolateProperties(double a, double b, double t1, double t2) {
+        // The interpolate function assumes t in (0, 1) and a <= b.
+        // These assumptions allow the implementation to be simplified.
+        if (b < a) {
+            testInterpolateProperties(b, a, t1, t2);
+            return;
+        }
+
+        // Test properties given arguments are finite.
+        // exactness: lerp(a,b,0)==a && lerp(a,b,1)==b
+        // monotonicity: cmp(lerp(a,b,t2),lerp(a,b,t1)) * cmp(t2,t1) * cmp(b,a) >= 0, where cmp
+        //               is an arithmetic three-way comparison function
+        // determinacy: result of NaN only for lerp(a,a,INFINITY)
+        // boundedness: t<0 || t>1 || isfinite(lerp(a,b,t))
+        // consistency: lerp(a,a,t)==a
+        // See: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0811r2.html
+
+        // Defined as x = a + t(b-a) but implementation may vary
+
+        // Interpolation between a==-0.0 and b>=0.0 is 0.0.
+        // This is known behaviour and ignored as usage has t in (0, 1).
+        if (Double.compare(a, -0.0) == 0 && Double.compare(b, 0.0) >= 0) {
+            Assertions.assertEquals(a, DoubleMath.interpolate(a, b, 0), 0.0, "exactness");
+        } else {
+            // result is -0.0 if a=b=-0.0
+            Assertions.assertEquals(a, DoubleMath.interpolate(a, b, 0), "exactness");
+        }
+        // Not supported
+        //Assertions.assertEquals(b, DoubleMath.interpolate(a, b, 1));
+        Assertions.assertTrue(
+            Double.compare(DoubleMath.interpolate(a, b, t2), DoubleMath.interpolate(a, b, t1)) *
+                Double.compare(t2, t1) * Double.compare(b, a) >= 0, "monotonicity");
+        final double m = Double.MAX_VALUE;
+        Assertions.assertTrue(Double.isFinite(DoubleMath.interpolate(a * m, b * m, t1)), "boundedness");
+        Assertions.assertTrue(Double.isFinite(DoubleMath.interpolate(a * m, b * m, t2)), "boundedness");
+        Assertions.assertEquals(a, DoubleMath.interpolate(a, a, t1), "consistency");
+        Assertions.assertEquals(b, DoubleMath.interpolate(b, b, t1), "consistency");
+    }
+
+    static Stream<Arguments> testInterpolateProperties() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
+        for (int i = 0; i < 50; i++) {
+            final double a = signedDouble(rng);
+            final double b = signedDouble(rng);
+            final double t1 = rng.nextDouble();
+            final double t2 = rng.nextDouble();
+            builder.add(Arguments.of(a, b, t1, t2));
+            builder.add(Arguments.of(a * 0.0, b, t1, t2));
+            builder.add(Arguments.of(a, b * 0.0, t1, t2));
+            builder.add(Arguments.of(a * 0.0, b * 0.0, t1, t2));
+        }
+        return builder.build();
+    }
+
+    @ParameterizedTest
+    @MethodSource
+    void testInterpolateEdge(double a, double b) {
+        if (b < a) {
+            testInterpolateEdge(b, a);
+            return;
+        }
+        // Test the extremes of t in (0, 1)
+        Assertions.assertTrue(DoubleMath.interpolate(a, b, 0.0) >= a, () -> "t=0 a=" + a + " b=" + b);
+        Assertions.assertTrue(DoubleMath.interpolate(a, b, Double.MIN_VALUE) >= a, () -> "t=min a=" + a + " b=" + b);
+        Assertions.assertTrue(DoubleMath.interpolate(a, b, Math.nextDown(1.0)) <= b, () -> "t=0.999... a=" + a + " b=" + b);
+        // This fails with the current implementation as it assumes interpolation never uses t=1
+        //Assertions.assertTrue(DoubleMath.interpolate(a, b, 1.0) <= b, () -> "t=1 a=" + a + " b=" + b);
+    }
+
+    static Stream<Arguments> testInterpolateEdge() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
+        final long infBits = Double.doubleToRawLongBits(Double.POSITIVE_INFINITY);
+        final long signBit = Long.MIN_VALUE;
+        for (int i = 0; i < 50; i++) {
+            builder.add(Arguments.of(signedDouble(rng), signedDouble(rng)));
+            // Any finite double
+            final long m = rng.nextLong(infBits);
+            final long n = rng.nextLong(infBits);
+            builder.add(Arguments.of(Double.longBitsToDouble(m), Double.longBitsToDouble(n)));
+            builder.add(Arguments.of(Double.longBitsToDouble(m), Double.longBitsToDouble(n | signBit)));
+            builder.add(Arguments.of(Double.longBitsToDouble(m | signBit), Double.longBitsToDouble(n)));
+            builder.add(Arguments.of(Double.longBitsToDouble(m | signBit), Double.longBitsToDouble(n | signBit)));
+        }
+        return builder.build();
+    }
+
+    @Test
+    void testSignedDouble() {
+        Assertions.assertEquals(-1.0, signedDouble(() -> Long.MIN_VALUE));
+        Assertions.assertEquals(Math.nextDown(1.0), signedDouble(() -> Long.MAX_VALUE));
+        Assertions.assertEquals(0.0, signedDouble(() -> 0));
+        Assertions.assertEquals(-Math.ulp(0.5), signedDouble(() -> -1L));
+        Assertions.assertEquals(Math.ulp(0.5), signedDouble(() -> 1L << 10));
+    }
+
+    /**
+     * Create a uniform signed double in [-1, 1). Spacing is 2^-53, or Math.ulp(0.5).
+     *
+     * @param rng Source of randomness.
+     * @return the double
+     */
+    private static double signedDouble(UniformRandomProvider rng) {
+        // As per UniformRandomProvider nextDouble but use a signed shift.
+        return 0x1.0p-53 * (rng.nextLong() >> 10);
+    }
+}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MedianTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MedianTest.java
new file mode 100644
index 0000000..f832f5b
--- /dev/null
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MedianTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.descriptive;
+
+import java.util.Arrays;
+import java.util.stream.Stream;
+import org.apache.commons.math3.stat.descriptive.rank.Percentile;
+import org.apache.commons.math3.stat.ranking.NaNStrategy;
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Test for {@link Median}.
+ */
+class MedianTest {
+    @Test
+    void testNullPropertyThrows() {
+        final Median m = Median.withDefaults();
+        Assertions.assertThrows(NullPointerException.class, () -> m.with((NaNPolicy) null));
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testMedian"})
+    void testMedian(double[] values, double expected) {
+        final double[] copy = values.clone();
+        Assertions.assertEquals(expected, Median.withDefaults().evaluate(values));
+        // Test the result and data (modified in-place) match the quantile implementation
+        Assertions.assertEquals(expected, Quantile.withDefaults().evaluate(copy, 0.5));
+        Assertions.assertArrayEquals(values, copy);
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testMedian"})
+    void testMedianExcludeNaN(double[] values, double expected) {
+        // If NaN is present then the result will change from expected so ignore this
+        Assumptions.assumeTrue(Arrays.stream(values).filter(Double::isNaN).count() == 0);
+        // Note: Use copy here. This checks that the copy of the data
+        // (with excluded NaNs) is used for special cases.
+        final Median m = Median.withDefaults().with(NaNPolicy.EXCLUDE).withCopy(true);
+        // Insert some "random" NaN data.
+        // Position can be in [0, n].
+        for (final int pos : new int[] {0, values.length >>> 1, values.length,
+                                        42 % (values.length + 1),
+                                        1267836813 % (values.length + 1)}) {
+            final double[] x = new double[values.length + 1];
+            System.arraycopy(values, 0, x, 0, pos);
+            x[pos] = Double.NaN;
+            System.arraycopy(values, pos, x, pos + 1, values.length - pos);
+            Assertions.assertEquals(expected, m.evaluate(x));
+        }
+    }
+
+    static Stream<Arguments> testMedian() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        final Percentile p = new Percentile(50).withNaNStrategy(NaNStrategy.FIXED);
+        // Note: Cannot use CM when NaN is adjacent to the middle of an odd length
+        // as it always interpolates pairs and uses: low + 0.0 * (NaN - low)
+        for (final double[] x : new double[][] {
+            {1},
+            {1, 2},
+            {2, 1},
+            {1, Double.NaN},
+            {Double.NaN, Double.NaN},
+            {1, Double.NaN, Double.NaN},
+            {1, 2, Double.NaN, Double.NaN},
+            {Double.NaN, Double.NaN, 1, 2, 3, 4},
+            {Double.MAX_VALUE, Double.MAX_VALUE},
+            {-Double.MAX_VALUE, -Double.MAX_VALUE / 2},
+        }) {
+            builder.add(Arguments.of(x, p.evaluate(x)));
+        }
+        // Cases where CM Percentile returns NaN
+        builder.add(Arguments.of(new double[]{1, 2, Double.NaN}, 2));
+        builder.add(Arguments.of(new double[]{Double.NaN, 1, 2, 3, Double.NaN}, 3));
+
+        // Test against the percentile can fail at 1 ULP so used a fixed seed
+        final UniformRandomProvider rng = RandomSource.XO_SHI_RO_128_PP.create(26378461823L);
+        // Sizes above and below the threshold for partitioning
+        double[] x;
+        for (final int size : new int[] {5, 6, 50, 51}) {
+            final double[] values = rng.doubles(size, -4.5, 1.5).toArray();
+            final double expected = p.evaluate(values);
+            for (int i = 0; i < 20; i++) {
+                x = TestHelper.shuffle(rng, values.clone());
+                builder.add(Arguments.of(x, expected));
+            }
+            // Special values
+            for (final double y : new double[] {-0.0, 0.0, 1, Double.MAX_VALUE,
+                Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN}) {
+                x = new double[size];
+                Arrays.fill(x, y);
+                builder.add(Arguments.of(x, y));
+            }
+            // Odd: just over half -0.0
+            // Even: half -0.0
+            x = new double[size];
+            Arrays.fill(x, 0, (size + 1) / 2, -0.0);
+            TestHelper.shuffle(rng, x);
+            builder.add(Arguments.of(x.clone(), (size & 0x1) == 1 ? -0.0 : 0.0));
+        }
+        // Special cases
+        builder.add(Arguments.of(new double[] {}, Double.NaN));
+        builder.add(Arguments.of(new double[] {-Double.MAX_VALUE, Double.MAX_VALUE}, 0));
+        builder.add(Arguments.of(new double[] {Double.MIN_VALUE, Double.MIN_VALUE}, Double.MIN_VALUE));
+        return builder.build();
+    }
+
+    @Test
+    void testMedianWithCopy() {
+        final double[] values = {3, 4, 2, 1, 0};
+        final double[] original = values.clone();
+        Assertions.assertEquals(2, Median.withDefaults().withCopy(true).evaluate(values));
+        Assertions.assertArrayEquals(original, values);
+        Assertions.assertEquals(2, Median.withDefaults().withCopy(false).evaluate(values));
+        Assertions.assertFalse(Arrays.equals(original, values));
+    }
+}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/NaNTransformersTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/NaNTransformersTest.java
new file mode 100644
index 0000000..d14634b
--- /dev/null
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/NaNTransformersTest.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.descriptive;
+
+import java.util.Arrays;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Test for {@link NaNTransformers}.
+ */
+class NaNTransformersTest {
+    @ParameterizedTest
+    @MethodSource(value = {"nanData"})
+    void testNaNErrorWithNaN(double[] a) {
+        final int[] bound = new int[1];
+        final NaNTransformer t1 = NaNTransformers.createNaNTransformer(NaNPolicy.ERROR, false);
+        Assertions.assertThrows(IllegalArgumentException.class, () -> t1.apply(a, bound));
+        final NaNTransformer t2 = NaNTransformers.createNaNTransformer(NaNPolicy.ERROR, true);
+        Assertions.assertThrows(IllegalArgumentException.class, () -> t2.apply(a, bound));
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"nonNanData"})
+    void testNaNError(double[] a) {
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.ERROR, false), true, false);
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.ERROR, true), true, true);
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"nanData", "nonNanData"})
+    void testNaNInclude(double[] a) {
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.INCLUDE, false), true, false);
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.INCLUDE, true), true, true);
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"nanData", "nonNanData"})
+    void testNaNExclude(double[] a) {
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.EXCLUDE, false), false, false);
+        assertNaNTransformer(a, NaNTransformers.createNaNTransformer(NaNPolicy.EXCLUDE, true), false, true);
+    }
+
+    /**
+     * Assert the NaN transformer allows including or excluding NaN.
+     *
+     * @param a Data.
+     * @param t Transformer.
+     * @param includeNaN True if the size should include NaN.
+     * @param copy True if the pre-processed data should be a copy.
+     */
+    private static void assertNaNTransformer(double[] a, NaNTransformer t,
+            boolean includeNaN, boolean copy) {
+        final int[] bounds = new int[1];
+        final double[] b = t.apply(a, bounds);
+        if (copy) {
+            Assertions.assertNotSame(a, b);
+        } else {
+            Assertions.assertSame(a, b);
+        }
+        // Count NaN
+        final int nanCount = (int) Arrays.stream(a).filter(Double::isNaN).count();
+        final int size = a.length - (includeNaN ? 0 : nanCount);
+        Assertions.assertEquals(size, bounds[0], "Size of data");
+        if (!includeNaN) {
+            for (int i = 0; i < size; i++) {
+                Assertions.assertNotEquals(Double.NaN, b[i], "NaN in unsorted range");
+            }
+            for (int i = size; i < b.length; i++) {
+                Assertions.assertEquals(Double.NaN, b[i], "non-NaN in upper range");
+            }
+        }
+    }
+
+    static Stream<double[]> nanData() {
+        final Stream.Builder<double[]> builder = Stream.builder();
+        final double nan = Double.NaN;
+        builder.add(new double[] {nan});
+        builder.add(new double[] {1, 2, nan});
+        builder.add(new double[] {nan, 2, 3});
+        builder.add(new double[] {1, nan, 3});
+        builder.add(new double[] {nan, nan});
+        builder.add(new double[] {nan, 2, nan});
+        builder.add(new double[] {nan, nan, nan});
+        builder.add(new double[] {1, 0.0, 0.0, nan, -1});
+        builder.add(new double[] {1, 0.0, -0.0, nan, -1});
+        builder.add(new double[] {1, -0.0, 0.0, nan, -1});
+        builder.add(new double[] {1, -0.0, -0.0, nan, -1});
+        builder.add(new double[] {1, 0.0, 0.0, nan, -1, 0.0, 0.0});
+        builder.add(new double[] {1, 0.0, -0.0, nan, -1, 0.0, 0.0});
+        builder.add(new double[] {1, 0.0, -0.0, nan, -1, 0.0, -0.0});
+        builder.add(new double[] {nan, -0.0, 0.0, nan, -1, -0.0, -0.0});
+        builder.add(new double[] {nan, -0.0, -0.0, nan, -1, -0.0, -0.0});
+        return builder.build();
+    }
+
+    static Stream<double[]> nonNanData() {
+        final Stream.Builder<double[]> builder = Stream.builder();
+        builder.add(new double[] {});
+        builder.add(new double[] {3});
+        builder.add(new double[] {3, 2, 1});
+        builder.add(new double[] {1, 0.0, 0.0, 3, -1});
+        builder.add(new double[] {1, 0.0, -0.0, 3, -1});
+        builder.add(new double[] {1, -0.0, 0.0, 3, -1});
+        builder.add(new double[] {1, -0.0, -0.0, 3, -1});
+        builder.add(new double[] {1, 0.0, 0.0, 3, -1, 0.0, 0.0});
+        builder.add(new double[] {1, 0.0, -0.0, 3, -1, 0.0, 0.0});
+        builder.add(new double[] {1, 0.0, -0.0, 3, -1, 0.0, -0.0});
+        builder.add(new double[] {1, -0.0, 0.0, 3, -1, -0.0, -0.0});
+        builder.add(new double[] {1, -0.0, -0.0, 3, -1, -0.0, -0.0});
+        return builder.build();
+    }
+}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/QuantileTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/QuantileTest.java
new file mode 100644
index 0000000..417dc08
--- /dev/null
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/QuantileTest.java
@@ -0,0 +1,392 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.descriptive;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+import org.apache.commons.statistics.descriptive.Quantile.EstimationMethod;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Test for {@link Quantile}.
+ */
+class QuantileTest {
+    /** Estimation types to test. */
+    private static final EstimationMethod[] TYPES = EstimationMethod.values();
+
+    /**
+     * Interface to test the quantile for a single probability.
+     */
+    interface QuantileFunction {
+        double evaluate(Quantile m, double[] values, double p);
+    }
+
+    /**
+     * Interface to test the quantiles for a multiple probabilities.
+     */
+    interface QuantileFunction2 {
+        double[] evaluate(Quantile m, double[] values, double[] p);
+    }
+
+    @Test
+    void testNullPropertyThrows() {
+        final Quantile m = Quantile.withDefaults();
+        Assertions.assertThrows(NullPointerException.class, () -> m.with((NaNPolicy) null));
+        Assertions.assertThrows(NullPointerException.class, () -> m.with((EstimationMethod) null));
+    }
+
+    @Test
+    void testProbabilitiesThrows() {
+        for (final int n : new int[] {-1, -42, Integer.MIN_VALUE}) {
+            Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(n));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(n, 0.5, 0.75));
+        }
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, -0.5, 0.75));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, 0.5, 1.75));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, 0.75, 0.75));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, 0.75, 0.5));
+        final double nan = Double.NaN;
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, nan, 0.5));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, 0.5, nan));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> Quantile.probabilities(1, nan, nan));
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testProbabilities"})
+    void testProbabilities(int n, double p1, double p2, double[] expected) {
+        Assertions.assertArrayEquals(expected, Quantile.probabilities(n, p1, p2), 1e-10);
+    }
+
+    static Stream<Arguments> testProbabilities() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        builder.add(Arguments.of(1, 0.0, 1.0, new double[] {0.5}));
+        builder.add(Arguments.of(2, 0.0, 1.0, new double[] {1.0 / 3, 2.0 / 3}));
+        builder.add(Arguments.of(5, 0.0, 1.0, new double[] {1.0 / 6, 2.0 / 6, 3.0 / 6, 4.0 / 6, 5.0 / 6}));
+        builder.add(Arguments.of(1, 0.25, 0.75, new double[] {0.5}));
+        builder.add(Arguments.of(2, 0.25, 0.75, new double[] {0.25 + 1.0 / 6, 0.25 + 2.0 / 6}));
+        builder.add(Arguments.of(1, 0.0, 0.5, new double[] {0.25}));
+        builder.add(Arguments.of(2, 0.0, 0.5, new double[] {1.0 / 6, 2.0 / 6}));
+        return builder.build();
+    }
+
+    @Test
+    void testBadQuantileThrows() {
+        final double[] values = {3, 4, 2, 1, 0};
+        final Quantile m = Quantile.withDefaults();
+        for (final double p : new double[] {-0.5, 1.2, Double.NaN}) {
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(values, p));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(values, new double[] {p}));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(10, i -> 1, p));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(10, i -> 1, new double[] {p}));
+        }
+    }
+
+    @Test
+    void testNoQuantilesThrows() {
+        final double[] values = {3, 4, 2, 1, 0};
+        final Quantile m = Quantile.withDefaults();
+        Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(values));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(values, new double[0]));
+        Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(10, i -> 1, new double[0]));
+    }
+
+    @Test
+    void testInvalidSizeThrows() {
+        final Quantile m = Quantile.withDefaults();
+        for (final int n : new int[] {-1, -42, Integer.MIN_VALUE}) {
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(n, i -> 1, 0.5));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> m.evaluate(n, i -> 1, 0.5, 0.75));
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testQuantile"})
+    void testQuantile(double[] values, double[] p, double[][] expected, double delta) {
+        assertQuantile(Quantile.withDefaults(), values, p, expected, delta,
+            Quantile::evaluate, Quantile::evaluate);
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testQuantile"})
+    void testQuantileExcludeNaN(double[] values, double[] p, double[][] expected, double delta) {
+        // If NaN is present then the result will change from expected so ignore this
+        Assumptions.assumeTrue(Arrays.stream(values).filter(Double::isNaN).count() == 0);
+        // Note: Use copy here. This checks that the copy of the data
+        // (with excluded NaNs) is used for special cases.
+        final Quantile q = Quantile.withDefaults().with(NaNPolicy.EXCLUDE).withCopy(true);
+        // Insert some "random" NaN data.
+        // Position can be in [0, n].
+        for (final int pos : new int[] {0, values.length >>> 1, values.length,
+                                        42 % (values.length + 1),
+                                        1267836813 % (values.length + 1)}) {
+            final double[] x = new double[values.length + 1];
+            System.arraycopy(values, 0, x, 0, pos);
+            x[pos] = Double.NaN;
+            System.arraycopy(values, pos, x, pos + 1, values.length - pos);
+            assertQuantile(q, x, p, expected, delta,
+                Quantile::evaluate, Quantile::evaluate);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource(value = {"testQuantile"})
+    void testQuantileSorted(double[] values, double[] p, double[][] expected, double delta) {
+        assertQuantile(Quantile.withDefaults(), values, p, expected, delta,
+            (m, x, q) -> {
+                // No clone here as later calls with the same array will also sort it
+                Arrays.sort(x);
+                return m.evaluate(x.length, i -> x[i], q);
+            },
+            (m, x, q) -> {
+                // No clone here as later calls with the same array will also sort it
+                Arrays.sort(x);
+                return m.evaluate(x.length, i -> x[i], q);
+            });
+    }
+
+    private static void assertQuantile(Quantile m, double[] values, double[] p,
+        double[][] expected, double delta,
+        QuantileFunction f1, QuantileFunction2 f2) {
+        Assertions.assertEquals(expected.length, TYPES.length);
+        for (int i = 0; i < TYPES.length; i++) {
+            final EstimationMethod type = TYPES[i];
+            m = m.with(type);
+            // Single quantiles
+            for (int j = 0; j < p.length; j++) {
+                if (f1 != null) {
+                    assertEqualsOrExactlyEqual(expected[i][j], f1.evaluate(m, values.clone(), p[j]), delta,
+                        () -> type.toString());
+                }
+                assertEqualsOrExactlyEqual(expected[i][j], f2.evaluate(m, values.clone(), new double[] {p[j]})[0], delta,
+                    () -> type.toString());
+            }
+            // Bulk quantiles
+            if (delta < 0) {
+                Assertions.assertArrayEquals(expected[i], f2.evaluate(m, values.clone(), p),
+                    () -> type.toString());
+            } else {
+                Assertions.assertArrayEquals(expected[i], f2.evaluate(m, values.clone(), p), delta,
+                    () -> type.toString());
+            }
+        }
+    }
+
+    /**
+     * Assert that {@code expected} and {@code actual} are equal within the given{@code delta}.
+     * If the {@code delta} is negative it is ignored and values must be exactly equal.
+     *
+     * @param expected Expected
+     * @param actual Actual
+     * @param delta Delta
+     * @param messageSupplier Failure message.
+     */
+    private static void assertEqualsOrExactlyEqual(double expected, double actual, double delta,
+        Supplier<String> messageSupplier) {
+        if (delta < 0) {
+            Assertions.assertEquals(expected, actual, messageSupplier);
+        } else {
+            Assertions.assertEquals(expected, actual, delta, messageSupplier);
+        }
+    }
+
+    static Stream<Arguments> testQuantile() {
+        final Stream.Builder<Arguments> builder = Stream.builder();
+        // Special cases
+        final double nan = Double.NaN;
+        addQuantiles(builder, new double[] {}, new double[] {0.75}, 1e-5,
+            new double[] {nan, nan, nan, nan, nan, nan, nan, nan, nan});
+        addQuantiles(builder, new double[] {42}, new double[] {0.75}, 1e-5,
+            new double[] {42, 42, 42, 42, 42, 42, 42, 42, 42});
+        // Cases from Commons Math PercentileTest
+        addQuantiles(builder, new double[] {1, 2, 3}, new double[] {0.75}, 1e-5,
+            new double[] {3, 3, 2, 2.25, 2.75, 3, 2.5, 2.83333, 2.81250});
+        addQuantiles(builder, new double[] {0, 1}, new double[] {0.25}, 1e-5,
+            new double[] {0, 0, 0, 0, 0, 0, 0.25, 0, 0});
+        final double[] d = new double[] {1, 3, 2, 4};
+        addQuantiles(builder, d, new double[] {0.3, 0.25, 0.75, 0.5}, 1e-5,
+            new double[] {2, 2, 1, 1.2, 1.7, 1.5, 1.9, 1.63333, 1.65},
+            new double[] {1, 1.5, 1, 1, 1.5, 1.25, 1.75, 1.41667, 1.43750},
+            new double[] {3, 3.5, 3, 3, 3.5, 3.75, 3.25, 3.58333, 3.56250},
+            new double[] {2, 2.5, 2, 2, 2.5, 2.5, 2.5, 2.5, 2.5});
+        // NIST example
+        addQuantiles(builder,
+            new double[] {95.1772, 95.1567, 95.1937, 95.1959, 95.1442, 95.0610, 95.1591, 95.1195, 95.1772, 95.0925,
+                95.1990, 95.1682},
+            new double[] {0.9}, 1e-4,
+            new double[] {95.19590, 95.19590, 95.19590, 95.19546, 95.19683, 95.19807, 95.19568, 95.19724, 95.19714});
+        addQuantiles(builder,
+            new double[] {12.5, 12.0, 11.8, 14.2, 14.9, 14.5, 21.0, 8.2, 10.3, 11.3, 14.1, 9.9, 12.2, 12.0, 12.1, 11.0,
+                19.8, 11.0, 10.0, 8.8, 9.0, 12.3},
+            new double[] {0.05}, 1e-4,
+            new double[] {8.8000, 8.8000, 8.2000, 8.2600, 8.5600, 8.2900, 8.8100, 8.4700, 8.4925});
+        // Special values tests
+        addQuantiles(builder,
+            new double[] {nan},
+            new double[] {0.5}, 1e-4,
+            new double[] {nan, nan, nan, nan, nan, nan, nan, nan, nan});
+        addQuantiles(builder,
+            new double[] {nan, nan},
+            new double[] {0.5}, 1e-4,
+            new double[] {nan, nan, nan, nan, nan, nan, nan, nan, nan});
+        addQuantiles(builder,
+            new double[] {1, nan},
+            new double[] {0.5}, 1e-4,
+            new double[] {1, nan, 1, 1, nan, nan, nan, nan, nan});
+        addQuantiles(builder,
+            new double[] {1, 2, nan},
+            new double[] {0.5}, 1e-4,
+            new double[] {2, 2, 2, 1.5, 2, 2, 2, 2, 2});
+        addQuantiles(builder,
+            new double[] {1, 2, nan, nan},
+            new double[] {0.5}, 1e-4,
+            new double[] {2, nan, 2, 2, nan, nan, nan, nan, nan});
+        // min/max test. This hits edge cases for bounds clipping when computing
+        // the index in [0, n).
+        addQuantiles(builder,
+            new double[] {5, 4, 3, 2, 1},
+            new double[] {0.0, 1.0}, 0.0,
+            new double[] {1, 1, 1, 1, 1, 1, 1, 1, 1},
+            new double[] {5, 5, 5, 5, 5, 5, 5, 5, 5});
+        // Note: This tests interpolation between -0.0 and -0.0, and -0.0 and 0.0.
+        // When the quantile requires interpolation, the sign should be maintained
+        // if the upper bound is -0.0.
+        // No interpolation
+        addQuantiles(builder,
+            new double[] {-0.0, 0.0, 0.0},
+            new double[] {0.0}, -1,
+            new double[] {-0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0});
+        // Interpolation between negative zeros
+        addQuantiles(builder,
+            new double[] {-0.0, -0.0, -0.0, -0.0, -0.0},
+            new double[] {0.45}, -1,
+            new double[] {-0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0});
+        // Interpolation between -0.0 and 0.0
+        addQuantiles(builder,
+            new double[] {-0.0, -0.0, 0.0, 0.0, 0.0},
+            new double[] {0.45}, -1,
+            // Here only HF3 rounds to k=2; other discrete methods to k=3;
+            // all continuous distributions interpolate to 0.0
+            new double[] {0.0, 0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0});
+
+        // Test data samples using R version 4.3.3
+        // require(stats)
+        // x = c(1, 2, 3)               %% data
+        // p = c(0.1, 0.25, 0.5, 0.975) %% probabilities
+        // for (t in c(1:9)) { cat('{', paste(quantile(x, p, type=t), collapse=', '), "}, \n", sep="") }
+
+        final double[] p = {0.1, 0.25, 0.5, 0.975};
+
+        // Use some of the standard data from BaseDoubleStatisticTest
+
+        /** Poisson samples: scipy.stats.poisson.rvs(45, size=100). */
+        final double[] v4 = {42, 51, 38, 38, 49, 48, 42, 47, 51, 46, 45, 35, 39, 42, 49, 55, 53, 46, 49, 56,
+            42, 46, 42, 53, 43, 55, 49, 52, 51, 45, 40, 49, 39, 40, 46, 43, 46, 48, 36, 44, 40, 49, 49, 43, 45, 44, 41, 55,
+            52, 45, 57, 41, 43, 44, 38, 52, 44, 45, 43, 42, 38, 37, 47, 42, 47, 45, 70, 45, 50, 47, 46, 50, 47, 35, 43, 52,
+            51, 41, 45, 42, 45, 53, 46, 48, 51, 43, 63, 48, 49, 41, 58, 51, 59, 43, 39, 32, 35, 46, 50, 50};
+
+        builder.add(Arguments.of(v4, p, new double[][] {
+            {38, 42, 46, 59},
+            {38.5, 42, 46, 59},
+            {38, 42, 46, 59},
+            {38, 42, 46, 58.5},
+            {38.5, 42, 46, 59},
+            {38.1, 42, 46, 60.9},
+            {38.9, 42, 46, 58.525},
+            {38.3666666666667, 42, 46, 59.6333333333333},
+            {38.4, 42, 46, 59.475},
+        }, 1e-13));
+
+        /** Normal samples: scipy.stats.norm.rvs(loc=3.4, scale=2.25, size=100). */
+        final double[] v5 = {1.06356579, -1.52552007, 7.09739891, -0.41516549, 0.17131653, 0.77923148,
+            2.90491862, 4.12648256, 5.04920689, 4.20053484, 5.83485097, 4.33138009, 4.18795702, 3.269289, 2.2399589,
+            4.16551591, -1.67192439, 1.44919254, 3.52270229, -1.49186865, -0.30794835, 5.82394621, 4.84755567, 4.79622486,
+            5.12461983, 2.62561931, 5.12457788, 8.24460895, 4.91249002, 3.75550863, 4.35440479, 4.17587334, -0.34934393,
+            2.98071452, -1.35620308, 1.93956508, 7.57171999, 5.41976186, 2.8427556, 3.04101193, 2.20374721, 4.65406057,
+            5.76961878, 3.14412957, 7.60322297, 1.598286, 2.51552974, 0.67767289, 0.76514432, 3.65663671, 0.53116457,
+            2.79439061, 7.58564809, 4.16735822, 2.95210392, 6.37867376, 6.57010411, 0.11837698, 9.16270054, 3.80097588,
+            5.48811672, 3.83378268, 2.03669252, 5.34865676, 3.11338528, 4.70088345, 6.00069684, 0.16144587, 4.22654482,
+            2.2722623, 5.39142224, 0.811471, 2.74523433, 6.32457234, 0.73033045, 9.54402353, 0.4800466, 2.00806359,
+            6.06115109, 2.3072464, 5.40974674, 2.05533169, 0.97160161, 8.06915145, 4.40792026, 4.53139251, 3.32350119,
+            1.53645238, 3.49059212, 3.57904997, 0.58634639, 5.87567911, 3.49424866, 5.72228178, 4.41403447, 1.27815121,
+            7.13861948, 4.68209093, 6.4598438, 0.66270586};
+
+        builder.add(Arguments.of(v5, p, new double[][] {
+            {0.17131653, 1.598286, 3.57904997, 8.24460895},
+            {0.325681565, 1.76892554, 3.61784334, 8.24460895},
+            {0.17131653, 1.598286, 3.57904997, 8.24460895},
+            {0.17131653, 1.598286, 3.57904997, 8.1568802},
+            {0.325681565, 1.76892554, 3.61784334, 8.24460895},
+            {0.202189537, 1.68360577, 3.61784334, 8.68070245524999},
+            {0.449173593, 1.85424531, 3.61784334, 8.1612666375},
+            {0.284517555666667, 1.74048561666667, 3.61784334, 8.38997345175},
+            {0.294808558, 1.7475955975, 3.61784334, 8.35363232631249},
+        }, 1e-14));
+
+        return builder.build();
+    }
+
+    /**
+     * Adds the quantiles.
+     *
+     * @param builder Builder.
+     * @param x Data.
+     * @param p Quantiles to compute.
+     * @param expected Expected result for each p for every estimation type.
+     */
+    private static void addQuantiles(Stream.Builder<Arguments> builder,
+        double[] x, double[] p, double delta, double[]... expected) {
+        Assertions.assertEquals(p.length, expected.length);
+        for (final double[] e : expected) {
+            Assertions.assertEquals(e.length, TYPES.length);
+        }
+        // Transpose
+        final double[][] t = new double[TYPES.length][p.length];
+        for (int i = 0; i < t.length; i++) {
+            for (int j = 0; j < p.length; j++) {
+                t[i][j] = expected[j][i];
+            }
+        }
+        builder.add(Arguments.of(x, p, t, delta));
+    }
+
+    @Test
+    void testQuantileWithCopy() {
+        final double[] values = {3, 4, 2, 1, 0};
+        final double[] original = values.clone();
+        Assertions.assertEquals(2, Quantile.withDefaults().withCopy(true).evaluate(values, 0.5));
+        Assertions.assertArrayEquals(original, values);
+        Assertions.assertEquals(2, Quantile.withDefaults().withCopy(false).evaluate(values, 0.5));
+        Assertions.assertFalse(Arrays.equals(original, values));
+    }
+
+    @Test
+    void testQuantileWithCopy2() {
+        final double[] values = {3, 4, 2, 1, 0};
+        final double[] original = values.clone();
+        Assertions.assertEquals(2, Quantile.withDefaults().withCopy(true).evaluate(values, new double[] {0.5})[0]);
+        Assertions.assertArrayEquals(original, values);
+        Assertions.assertEquals(2, Quantile.withDefaults().withCopy(false).evaluate(values, new double[] {0.5})[0]);
+        Assertions.assertFalse(Arrays.equals(original, values));
+    }
+}
diff --git a/commons-statistics-examples/examples-jmh/pom.xml b/commons-statistics-examples/examples-jmh/pom.xml
index ce3319e..4e79c1a 100644
--- a/commons-statistics-examples/examples-jmh/pom.xml
+++ b/commons-statistics-examples/examples-jmh/pom.xml
@@ -51,6 +51,11 @@
       <artifactId>commons-rng-simple</artifactId>
     </dependency>
 
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-rng-sampling</artifactId>
+    </dependency>
+
     <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-numbers-fraction</artifactId>
@@ -61,6 +66,17 @@
       <artifactId>commons-numbers-rootfinder</artifactId>
     </dependency>
 
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-math3</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-math4-legacy</artifactId>
+      <version>${statistics.commons.math4.version}</version>
+    </dependency>
+
     <dependency>
       <groupId>org.openjdk.jmh</groupId>
       <artifactId>jmh-core</artifactId>
diff --git a/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/MedianPerformance.java b/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/MedianPerformance.java
new file mode 100644
index 0000000..760b4ec
--- /dev/null
+++ b/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/MedianPerformance.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.examples.jmh.descriptive;
+
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import java.util.function.ToDoubleFunction;
+import org.apache.commons.statistics.descriptive.Median;
+import org.apache.commons.statistics.examples.jmh.descriptive.QuantilePerformance.AbstractDataSource;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+
+/**
+ * Executes a benchmark of the creation of a median from array data.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@State(Scope.Benchmark)
+@Fork(value = 1, jvmArgs = {"-server", "-Xms512M", "-Xmx8192M"})
+public class MedianPerformance {
+    /** Use the JDK sort function. */
+    private static final String JDK = "JDK";
+    /** Commons Math 3 Percentile implementation. */
+    private static final String CM3 = "CM3";
+    /** Commons Math 4 Percentile implementation. */
+    private static final String CM4 = "CM4";
+    /** Commons Statistics implementation. */
+    private static final String STATISTICS = "Statistics";
+
+    /**
+     * Source of {@code double} array data.
+     *
+     * <p>This uses the same data class as {@link QuantilePerformance}.
+     * This enables reuse of the various data distributions provided.
+     */
+    @State(Scope.Benchmark)
+    public static class DataSource extends AbstractDataSource {
+        /** Data length. */
+        @Param({"1000", "100000"})
+        private int length;
+
+        /** {@inheritDoc} */
+        @Override
+        protected int getLength() {
+            return length;
+        }
+    }
+
+    /**
+     * Source of a {@link ToDoubleFunction} for a {@code double[]}.
+     */
+    @State(Scope.Benchmark)
+    public static class DoubleFunctionSource {
+        /** Name of the source. */
+        @Param({JDK, CM3, CM4, STATISTICS})
+        private String name;
+
+        /** The action. */
+        private ToDoubleFunction<double[]> function;
+
+        /**
+         * @return the function
+         */
+        public ToDoubleFunction<double[]> getFunction() {
+            return function;
+        }
+
+        /**
+         * Create the function.
+         */
+        @Setup
+        public void setup() {
+            // Note: Functions defensively copy the data by default
+            // Note: KeyStratgey does not matter for single / paired keys but
+            // we set it anyway for completeness.
+            Objects.requireNonNull(name);
+            if (JDK.equals(name)) {
+                function = MedianPerformance::sortMedian;
+            } else if (CM3.equals(name)) {
+                final org.apache.commons.math3.stat.descriptive.rank.Median m =
+                    new org.apache.commons.math3.stat.descriptive.rank.Median();
+                function = m::evaluate;
+            } else if (CM4.equals(name)) {
+                final org.apache.commons.math4.legacy.stat.descriptive.rank.Median m =
+                    new org.apache.commons.math4.legacy.stat.descriptive.rank.Median();
+                function = m::evaluate;
+            } else if (STATISTICS.equals(name)) {
+                function = Median.withDefaults()::evaluate;
+            } else {
+                throw new IllegalStateException("Unknown double[] function: " + name);
+            }
+        }
+    }
+
+    /**
+     * Sort the values and compute the median.
+     *
+     * @param values Values.
+     * @return the median
+     */
+    static double sortMedian(double[] values) {
+        // Implicit NPE
+        final int n = values.length;
+        // Special cases
+        if (n <= 2) {
+            switch (n) {
+            case 2:
+                return (values[0] + values[1]) * 0.5;
+            case 1:
+                return values[0];
+            default:
+                return Double.NaN;
+            }
+        }
+        // A sort is required
+        Arrays.sort(values);
+        final int k = n >>> 1;
+        // Odd
+        if ((n & 0x1) == 0x1) {
+            return values[k];
+        }
+        // Even
+        return (values[k - 1] + values[k]) * 0.5;
+    }
+
+    /**
+     * Create the statistic using an array.
+     *
+     * @param function Source of the function.
+     * @param source Source of the data.
+     * @param bh Data sink.
+     */
+    @Benchmark
+    public void median(DoubleFunctionSource function, DataSource source, Blackhole bh) {
+        final int size = source.size();
+        final ToDoubleFunction<double[]> fun = function.getFunction();
+        for (int j = -1; ++j < size;) {
+            bh.consume(fun.applyAsDouble(source.getData(j)));
+        }
+    }
+}
diff --git a/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformance.java b/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformance.java
new file mode 100644
index 0000000..a5a16e1
--- /dev/null
+++ b/commons-statistics-examples/examples-jmh/src/main/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformance.java
@@ -0,0 +1,1064 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.examples.jmh.descriptive;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BinaryOperator;
+import java.util.logging.Logger;
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.sampling.PermutationSampler;
+import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler;
+import org.apache.commons.rng.sampling.distribution.SharedStateDiscreteSampler;
+import org.apache.commons.rng.simple.RandomSource;
+import org.apache.commons.statistics.descriptive.Quantile;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+
+/**
+ * Executes a benchmark of the creation of a quantile from array data.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@State(Scope.Benchmark)
+@Fork(value = 1, jvmArgs = {"-server", "-Xms512M", "-Xmx8192M"})
+public class QuantilePerformance {
+    /** Use the JDK sort function. */
+    private static final String JDK = "JDK";
+    /** Commons Math 3 Percentile implementation. */
+    private static final String CM3 = "CM3";
+    /** Commons Math 4 Percentile implementation. */
+    private static final String CM4 = "CM4";
+    /** Commons Statistics implementation. */
+    private static final String STATISTICS = "Statistics";
+
+    /** Random source. */
+    private static final RandomSource RANDOM_SOURCE = RandomSource.XO_RO_SHI_RO_128_PP;
+
+    /**
+     * Source of {@code double} array data.
+     *
+     * <p>By default this uses the adverse input test suite from figure 1 in Bentley and McIlroy
+     * (1993) Engineering a sort function, Software, practice and experience, Vol.23(11),
+     * 1249–1265.
+     *
+     * <p>An alternative set of data is from Valois (2000) Introspective sorting and selection
+     * revisited, Software, practice and experience, Vol.30(6), 617-638.
+     *
+     * <p>Note
+     *
+     * <p>This data source has been adapted from {@code o.a.c.numbers.examples.jmh.arrays}.
+     *
+     * <p>Random distribution mode
+     *
+     * <p>The default BM configuration includes random samples generated as a family of
+     * single samples created from ranges that are powers of two [0, 2^i). This small set
+     * of samples is only a small representation of randomness. For small lengths this may
+     * only be a few random samples.
+     *
+     * <p>The data source can be changed to generate a fixed number of random samples
+     * using a uniform distribution [0, n]. For this purpose the distribution must be set
+     * to {@link Distribution#RANDOM} and the {@code samples} set above
+     * zero. The inclusive upper bound {@code n} is set using the {@code seed}.
+     * If this is zero then the default is {@link Integer#MAX_VALUE}.
+     */
+    @State(Scope.Benchmark)
+    public abstract static class AbstractDataSource {
+        /** All distributions / modifications. */
+        private static final String ALL = "all";
+        /** All distributions / modifications in the Bentley and McIlroy test suite. */
+        private static final String BM = "bm";
+        /** All distributions in the Valois test suite. These currently ignore the seed.
+         * To replicate Valois used a fixed seed and the copy modification. */
+        private static final String VALOIS = "valois";
+        /** Flag to determine if the data size should be logged. This is useful to be
+         * able to determine the execution time per sample when the number of samples
+         * is dynamically created based on the data length, range and seed. */
+        private static final AtomicInteger LOG_SIZE = new AtomicInteger();
+
+        /**
+         * The type of distribution.
+         */
+        enum Distribution {
+            // B&M (1993)
+
+            /** sawtooth distribution. */
+            SAWTOOTH,
+            /** random distribution. */
+            RANDOM,
+            /** stagger distribution. */
+            STAGGER,
+            /** plateau distribution. */
+            PLATEAU,
+            /** shuffle distribution. */
+            SHUFFLE,
+
+            /** sharktooth distribution. This is an addition to the original suite of B & M
+             * and is not included in the test suite by default and must be specified.
+             *
+             * <p>An ascending then descending sequence is also known as organpipe in
+             * Valois (2000),
+             * Introspective sorting and selection revisited,
+             * Software–Practice and Experience 30, 617–638.
+             * This version allows multiple ascending/descending runs in the same length. */
+            SHARKTOOTH,
+
+            // Valois (2000)
+
+            /** Sorted. */
+            SORTED,
+            /** Permutation of ones and zeros. */
+            ONEZERO,
+            /** Musser's median-of-3 killer. */
+            M3KILLER,
+            /** A sorted sequence rotated left once. */
+            ROTATED,
+            /** Musser's two-faced sequence (the median-of-3 killer with two random permutations). */
+            TWOFACED,
+            /** An ascending then descending sequence. */
+            ORGANPIPE;
+        }
+
+        /**
+         * The type of data modification.
+         */
+        enum Modification {
+            /** copy modification. */
+            COPY,
+            /** reverse modification. */
+            REVERSE,
+            /** reverse front-half modification. */
+            REVERSE_FRONT,
+            /** reverse back-half modification. */
+            REVERSE_BACK,
+            /** sort modification. */
+            SORT,
+            /** descending modification (this is an addition to the original suite of B & M).
+             * It is useful for testing worst case performance, e.g. insertion sort performs
+             * poorly on descending data. Heapselect using a max heap would perform poorly
+             * if data is processed in the forward direction as all elements must be inserted.
+             *
+             * <p>This is not included in the test suite by default and must be specified.
+             * Note that the Shuffle distribution with a very large seed 'm' is effectively an
+             * ascending sequence and will be reversed to descending as part of the original
+             * B&M suite of data. */
+            DESCENDING,
+            /** dither modification. */
+            DITHER;
+        }
+
+        /** Order. This is randomized to ensure that successive calls do not partition
+         * similar distributions. Randomized per invocation to avoid the JVM 'learning'
+         * branch decisions to take in small data sets. */
+        protected int[] order;
+        /** Cached source of randomness. */
+        protected UniformRandomProvider rng;
+
+        /** Type of data. Multiple types can be specified in the same string using
+         * lower/upper case, delimited using ':'. */
+        @Param({BM})
+        private String distribution = BM;
+
+        /** Type of data modification. Multiple types can be specified in the same string using
+         * lower/upper case, delimited using ':'. */
+        @Param({BM})
+        private String modification = BM;
+
+        /** Extra range to add to the data length.
+         * E.g. Use 1 to force use of odd and even length samples for the median. */
+        @Param({"1"})
+        private int range = 1;
+
+        /** Sample 'seed'. This is {@code m} in Bentley and McIlroy's test suite.
+         * If set to zero the default is to use powers of 2 based on sample size. */
+        @Param({"0"})
+        private int seed;
+
+        /** Sample offset. This is used to shift each distribution to create different data.
+         * It is advanced on each invocation of {@link #setup()}. */
+        @Param({"0"})
+        private int offset;
+
+        /** Number of samples. Applies only to the random distribution. In this case
+         * the length of the data is randomly chosen in {@code [length, length + range)}. */
+        @Param({"0"})
+        private int samples;
+
+        /** RNG seed. Created using ThreadLocalRandom.current().nextLong(). This is advanced
+         * for the random distribution mode per iteration. Each benchmark executed by
+         * JMH will use the same random data, even across JVMs.
+         *
+         * <p>If this is zero then a random seed is chosen. */
+        @Param({"-7450238124206088695"})
+        private long rngSeed = -7450238124206088695L;
+
+        /** Data. This is stored as integer data which saves memory. Note that when ranking
+         * data it is not necessary to have the full range of the double data type; the same
+         * number of unique values can be recorded in an array using an integer type.
+         * Returning a double[] forces a copy to be generated for destructive sorting /
+         * partitioning methods. */
+        private int[][] data;
+
+        /**
+         * Gets the sample for the given {@code index}.
+         *
+         * <p>This is returned in a randomized order per iteration.
+         *
+         * @param index Index.
+         * @return the data sample
+         */
+        public double[] getData(int index) {
+            return getDataSample(order[index]);
+        }
+
+        /**
+         * Gets the sample for the given {@code index}.
+         *
+         * @param index Index.
+         * @return the data sample
+         */
+        protected double[] getDataSample(int index) {
+            final int[] a = data[index];
+            final double[] x = new double[a.length];
+            for (int i = -1; ++i < a.length;) {
+                x[i] = a[i];
+            }
+            return x;
+        }
+
+        /**
+         * Gets the sample size for the given {@code index}.
+         *
+         * @param index Index.
+         * @return the data sample size
+         */
+        public int getDataSize(int index) {
+            return data[index].length;
+        }
+
+        /**
+         * Get the number of data samples.
+         *
+         * <p>Note: This data source will create a permutation order per invocation based on
+         * this size. Per-invocation control in JMH is recommended for methods that take
+         * more than 1 millisecond to execute. For very small data and/or fast methods
+         * this may not be achievable. Child classes may override this value to create
+         * a large number of repeats of the same data per invocation. Any class performing
+         * this should also override {@link #getData(int)} to prevent index out of bound errors.
+         * This can be done by mapping the index to the original index using the number of repeats
+         * e.g. {@code original index = index / repeats}.
+         *
+         * @return the number of samples
+         */
+        public int size() {
+            return data.length;
+        }
+
+        /**
+         * Create the data.
+         */
+        @Setup(Level.Iteration)
+        public void setup() {
+            Objects.requireNonNull(distribution);
+            Objects.requireNonNull(modification);
+
+            // Set-up using parameters (may throw)
+            final EnumSet<Distribution> dist = getDistributions();
+            final int length = getLength();
+            if (length < 1) {
+                throw new IllegalStateException("Unsupported length: " + length);
+            }
+            // Note: Bentley-McIlroy use n in {100, 1023, 1024, 1025}.
+            // Here we only support a continuous range. The range is important
+            // for the median as it will require one or two points to partition
+            // if the length is odd or even.
+            final int r = range > 0 ? range : 0;
+            if (length + (long) r > Integer.MAX_VALUE) {
+                throw new IllegalStateException("Unsupported upper length: " + length);
+            }
+            final int length2 = length + r;
+
+            // Allow pseudorandom seeding
+            if (rngSeed == 0) {
+                rngSeed = RandomSource.createLong();
+            }
+            if (rng == null) {
+                // First call, create objects
+                rng = RANDOM_SOURCE.create(rngSeed);
+            }
+
+            // Special case for random distribution mode
+            if (dist.contains(Distribution.RANDOM) && dist.size() == 1 && samples > 0) {
+                data = new int[samples][];
+                final int upper = seed > 0 ? seed : Integer.MAX_VALUE;
+                final SharedStateDiscreteSampler s1 = DiscreteUniformSampler.of(rng, 0, upper);
+                final SharedStateDiscreteSampler s2 = DiscreteUniformSampler.of(rng, length, length2);
+                for (int i = 0; i < data.length; i++) {
+                    final int[] a = new int[s2.sample()];
+                    for (int j = a.length; --j >= 0;) {
+                        a[j] = s1.sample();
+                    }
+                    data[i] = a;
+                }
+                return;
+            }
+
+            // New data per iteration
+            data = null;
+            final int o = offset;
+            offset = rng.nextInt();
+
+            final EnumSet<Modification> mod = getModifications();
+
+            // Data using the RNG will be randomized only once.
+            // Here we use the same seed for parity across methods.
+            // Note that most distributions do not use the source of randomness.
+            final ArrayList<int[]> sampleData = new ArrayList<>();
+            for (int n = length; n <= length2; n++) {
+                // Note: Large lengths may wish to limit the range of m to limit
+                // the memory required to store the samples. Currently a single
+                // m is supported via the seed parameter.
+                // Default seed will create ceil(log2(2*n)) * 5 dist * 6 mods samples:
+                // MAX  = 32 * 5 * 7 * (2^31-1) * 4 bytes == 7679 GiB
+                // HUGE = 31 * 5 * 7 * 2^30 * 4 bytes == 3719 GiB
+                // BIG  = 21 * 5 * 7 * 2^20 * 4 bytes == 2519 MiB  <-- within configured JVM -Xmx
+                // MED  = 11 * 5 * 7 * 2^10 * 4 bytes == 1318 KiB
+                // (This excludes the descending modification.)
+                // It is possible to create lengths above 2^30 using a single distribution,
+                // modification, and seed:
+                // MAX1 = 1 * 1 * 1 * (2^31-1) * 4 bytes == 8191 MiB
+                // However this is then used to create double[] data thus requiring an extra
+                // ~16GiB memory for the sample to partition.
+                for (final int m : createSeeds(seed, n)) {
+                    final List<int[]> d = createDistributions(dist, rng, n, m, o);
+                    for (int i = 0; i < d.size(); i++) {
+                        final int[] x = d.get(i);
+                        if (mod.contains(Modification.COPY)) {
+                            // Don't copy! All other methods generate copies
+                            // so we can use this in-place.
+                            sampleData.add(x);
+                        }
+                        if (mod.contains(Modification.REVERSE)) {
+                            sampleData.add(reverse(x, 0, n));
+                        }
+                        if (mod.contains(Modification.REVERSE_FRONT)) {
+                            sampleData.add(reverse(x, 0, n >>> 1));
+                        }
+                        if (mod.contains(Modification.REVERSE_BACK)) {
+                            sampleData.add(reverse(x, n >>> 1, n));
+                        }
+                        // Only sort once
+                        if (mod.contains(Modification.SORT) ||
+                            mod.contains(Modification.DESCENDING)) {
+                            final int[] y = x.clone();
+                            Arrays.sort(y);
+                            if (mod.contains(Modification.DESCENDING)) {
+                                sampleData.add(reverse(y, 0, n));
+                            }
+                            if (mod.contains(Modification.SORT)) {
+                                sampleData.add(y);
+                            }
+                        }
+                        if (mod.contains(Modification.DITHER)) {
+                            sampleData.add(dither(x));
+                        }
+                    }
+                }
+            }
+            data = sampleData.toArray(int[][]::new);
+            if (LOG_SIZE.getAndSet(length) != length) {
+                Logger.getLogger(getClass().getName()).info(
+                    () -> String.format("Data length: [%d, %d] n=%d", length, length2, data.length));
+            }
+        }
+
+        /**
+         * Create the order to process the indices.
+         *
+         * <p>JMH recommends that invocations should take at
+         * least 1 millisecond for timings to be usable. In practice there should be
+         * enough data that processing takes much longer than a few milliseconds.
+         */
+        @Setup(Level.Invocation)
+        public void createOrder() {
+            if (order == null) {
+                // First call, create objects
+                order = PermutationSampler.natural(size());
+            }
+            PermutationSampler.shuffle(rng, order);
+        }
+
+        /**
+         * @return the distributions
+         */
+        private EnumSet<Distribution> getDistributions() {
+            EnumSet<Distribution> dist;
+            if (BM.equals(distribution)) {
+                dist = EnumSet.of(
+                    Distribution.SAWTOOTH,
+                    Distribution.RANDOM,
+                    Distribution.STAGGER,
+                    Distribution.PLATEAU,
+                    Distribution.SHUFFLE);
+            } else if (VALOIS.equals(distribution)) {
+                dist = EnumSet.of(
+                    Distribution.RANDOM,
+                    Distribution.SORTED,
+                    Distribution.ONEZERO,
+                    Distribution.M3KILLER,
+                    Distribution.ROTATED,
+                    Distribution.TWOFACED,
+                    Distribution.ORGANPIPE);
+            } else {
+                dist = getEnumFromParam(Distribution.class, distribution);
+            }
+            return dist;
+        }
+
+        /**
+         * @return the modifications
+         */
+        private EnumSet<Modification> getModifications() {
+            EnumSet<Modification> mod;
+            if (BM.equals(modification)) {
+                // Modifications are from Bentley and McIlroy
+                mod = EnumSet.allOf(Modification.class);
+                // ... except descending
+                mod.remove(Modification.DESCENDING);
+            } else if (VALOIS.equals(modification)) {
+                // For convenience alias Valois to copy
+                mod = EnumSet.of(Modification.COPY);
+            } else {
+                mod = getEnumFromParam(Modification.class, modification);
+            }
+            return mod;
+        }
+
+        /**
+         * Gets all the enum values of the given class from the parameters.
+         *
+         * @param <E> Enum type.
+         * @param cls Class of the enum.
+         * @param parameters Parameters (multiple values delimited by ':')
+         * @return the enum values
+         */
+        static <E extends Enum<E>> EnumSet<E> getEnumFromParam(Class<E> cls, String parameters) {
+            if (ALL.equals(parameters)) {
+                return EnumSet.allOf(cls);
+            }
+            final EnumSet<E> set = EnumSet.noneOf(cls);
+            final String s = parameters.toUpperCase(Locale.ROOT);
+            for (final E e : cls.getEnumConstants()) {
+                // Scan for the name
+                for (int i = s.indexOf(e.name(), 0); i >= 0; i = s.indexOf(e.name(), i)) {
+                    // Ensure a full match to the name:
+                    // either at the end of the string, or followed by the delimiter
+                    i += e.name().length();
+                    if (i == s.length() || s.charAt(i) == ':') {
+                        set.add(e);
+                        break;
+                    }
+                }
+            }
+            if (set.isEmpty()) {
+                throw new IllegalStateException("Unknown parameters: " + parameters);
+            }
+            return set;
+        }
+
+        /**
+         * Creates the seeds.
+         *
+         * <p>This can be pasted into a JShell terminal to verify it works for any size
+         * {@code 1 <= n < 2^31}. With the default behaviour all seeds {@code m} are
+         * strictly positive powers of 2 and the highest seed should be below {@code 2*n}.
+         *
+         * @param seed Seed (use 0 for default; or provide a strictly positive {@code 1 <= m <= 2^31}).
+         * @param n Sample size.
+         * @return the seeds
+         */
+        private static int[] createSeeds(int seed, int n) {
+            // Allow [1, 2^31] (note 2^31 is negative but handled as a power of 2)
+            if (seed - 1 >= 0) {
+                return new int[] {seed};
+            }
+            // Bentley-McIlroy use:
+            // for: m = 1; m < 2 * n; m *= 2
+            // This has been modified here to handle n up to MAX_VALUE
+            // by knowing the count of m to generate as the power of 2 >= n.
+
+            // ceil(log2(n)) + 1 == ceil(log2(2*n)) but handles MAX_VALUE
+            int c = 33 - Integer.numberOfLeadingZeros(n - 1);
+            final int[] seeds = new int[c];
+            c = 0;
+            for (int m = 1; c != seeds.length; m *= 2) {
+                seeds[c++] = m;
+            }
+            return seeds;
+        }
+
+        /**
+         * Creates the distribution samples. Handles {@code m = 2^31} using
+         * {@link Integer#MIN_VALUE}.
+         *
+         * <p>The offset is used to adjust each distribution to generate a different
+         * output. Only applies to distributions that do not use the source of randomness.
+         *
+         * <p>Distributions are generated in enum order and recorded in the output {@code sampleDist}.
+         * Distributions that are a constant value at {@code m == 1} are not generated.
+         * This case is handled by the plateau distribution which will be a constant value
+         * except one occurrence of zero.
+         *
+         * @param dist Distributions.
+         * @param rng Source of randomness.
+         * @param n Length of the sample.
+         * @param m Sample seed (in [1, 2^31])
+         * @param o Offset.
+         * @return the samples
+         */
+        private static List<int[]> createDistributions(EnumSet<Distribution> dist,
+                UniformRandomProvider rng, int n, int m, int o) {
+            final ArrayList<int[]> distData = new ArrayList<>(6);
+            int[] x;
+            // B&M (1993)
+            if (dist.contains(Distribution.SAWTOOTH) && m != 1) {
+                distData.add(x = new int[n]);
+                // i % m
+                // Typical case m is a power of 2 so we can use a mask
+                // Use the offset.
+                final int mask = m - 1;
+                if ((m & mask) == 0) {
+                    for (int i = -1; ++i < n;) {
+                        x[i] = (i + o) & mask;
+                    }
+                } else {
+                    // User input seed. Start at the offset.
+                    int j = Integer.remainderUnsigned(o, m);
+                    for (int i = -1; ++i < n;) {
+                        j = j % m;
+                        x[i] = j++;
+                    }
+                }
+            }
+            if (dist.contains(Distribution.RANDOM) && m != 1) {
+                distData.add(x = new int[n]);
+                // rand() % m
+                // A sampler is faster than rng.nextInt(m); the sampler has an inclusive upper.
+                final SharedStateDiscreteSampler s = DiscreteUniformSampler.of(rng, 0, m - 1);
+                for (int i = -1; ++i < n;) {
+                    x[i] = s.sample();
+                }
+            }
+            if (dist.contains(Distribution.STAGGER)) {
+                distData.add(x = new int[n]);
+                // Overflow safe: (i * m + i) % n
+                final long nn = n;
+                final long oo = Integer.toUnsignedLong(o);
+                for (int i = -1; ++i < n;) {
+                    final long j = i + oo;
+                    x[i] = (int) ((j * m + j) % nn);
+                }
+            }
+            if (dist.contains(Distribution.PLATEAU)) {
+                distData.add(x = new int[n]);
+                // min(i, m)
+                for (int i = Math.min(n, m); --i >= 0;) {
+                    x[i] = i;
+                }
+                for (int i = m - 1; ++i < n;) {
+                    x[i] = m;
+                }
+                // Rotate
+                final int n1 = Integer.remainderUnsigned(o, n);
+                if (n1 != 0) {
+                    final int[] a = x.clone();
+                    final int n2 = n - n1;
+                    System.arraycopy(a, 0, x, n1, n2);
+                    System.arraycopy(a, n2, x, 0, n1);
+                }
+            }
+            if (dist.contains(Distribution.SHUFFLE) && m != 1) {
+                distData.add(x = new int[n]);
+                // rand() % m ? (j += 2) : (k += 2)
+                final SharedStateDiscreteSampler s = DiscreteUniformSampler.of(rng, 0, m - 1);
+                for (int i = -1, j = 0, k = 1; ++i < n;) {
+                    x[i] = s.sample() != 0 ? (j += 2) : (k += 2);
+                }
+            }
+            // Extra - based on organpipe with a variable ascending/descending length
+            if (dist.contains(Distribution.SHARKTOOTH) && m != 1) {
+                distData.add(x = new int[n]);
+                // ascending-descending runs
+                int i = -1;
+                int j = (o & Integer.MAX_VALUE) % m - 1;
+                OUTER:
+                for (;;) {
+                    while (++j < m) {
+                        if (++i == n) {
+                            break OUTER;
+                        }
+                        x[i] = j;
+                    }
+                    while (--j >= 0) {
+                        if (++i == n) {
+                            break OUTER;
+                        }
+                        x[i] = j;
+                    }
+                }
+            }
+            // Valois (2000)
+            if (dist.contains(Distribution.SORTED)) {
+                distData.add(x = new int[n]);
+                for (int i = -1; ++i < n;) {
+                    x[i] = i;
+                }
+            }
+            if (dist.contains(Distribution.ONEZERO)) {
+                distData.add(x = new int[n]);
+                // permutation of floor(n/2) ones and ceil(n/2) zeroes.
+                // For convenience this uses random ones and zeros to avoid a shuffle
+                // and simply reads bits from integers. The distribution will not
+                // be exactly 50:50.
+                final int end = n & ~31;
+                for (int i = 0; i < end; i += 32) {
+                    int z = rng.nextInt();
+                    for (int j = -1; ++j < 32;) {
+                        x[i + j] = z & 1;
+                        z >>>= 1;
+                    }
+                }
+                for (int i = end; ++i < n;) {
+                    x[i] = rng.nextBoolean() ? 1 : 0;
+                }
+            }
+            if (dist.contains(Distribution.M3KILLER)) {
+                distData.add(x = new int[n]);
+                medianOf3Killer(x);
+            }
+            if (dist.contains(Distribution.ROTATED)) {
+                distData.add(x = new int[n]);
+                // sorted sequence rotated left once
+                // 1, 2, 3, ..., n-1, n, 0
+                for (int i = 0; i < n;) {
+                    x[i] = ++i;
+                }
+                x[n - 1] = 0;
+            }
+            if (dist.contains(Distribution.TWOFACED)) {
+                distData.add(x = new int[n]);
+                // Musser's two faced randomly permutes a median-of-3 killer in
+                // 4 floor(log2(n)) through n/2 and n/2 + 4 floor(log2(n)) through n
+                medianOf3Killer(x);
+                final int j = 4 * (31 - Integer.numberOfLeadingZeros(n));
+                final int n2 = n >>> 1;
+                shuffle(rng, x, j, n2);
+                shuffle(rng, x, n2 + j, n);
+            }
+            if (dist.contains(Distribution.ORGANPIPE)) {
+                distData.add(x = new int[n]);
+                // 0, 1, 2, 3, ..., 3, 2, 1, 0
+                // n should be even to leave two equal values in the middle, otherwise a single
+                for (int i = -1, j = n; ++i <= --j;) {
+                    x[i] = i;
+                    x[j] = i;
+                }
+            }
+            return distData;
+        }
+
+        /**
+         * Create Musser's median-of-3 killer sequence (in-place).
+         *
+         * @param x Data.
+         */
+        private static void medianOf3Killer(int[] x) {
+            // This uses the original K_2k sequence from Musser (1997)
+            // Introspective sorting and selection algorithms,
+            // Software—Practice and Experience, 27(8), 983–993.
+            // A true median-of-3 killer requires n to be an even integer divisible by 4,
+            // i.e. k is an even positive integer. This causes a median-of-3 partition
+            // strategy to produce a sequence of n/4 partitions into sub-sequences of
+            // length 2 and n-2, 2 and n-4, ..., 2 and n/2.
+            // 1   2   3   4   5       k-2   k-1  k   k+1 k+2 k+3     2k-1  2k
+            // 1, k+1, 3, k+3, 5, ..., 2k-3, k-1 2k-1  2   4   6  ... 2k-2  2k
+            final int n = x.length;
+            final int k = n >>> 1;
+            for (int i = 0; i < k; i++) {
+                x[i] = ++i;
+                x[i] = k + i;
+            }
+            for (int i = k - 1, j = 2; ++i < n; j += 2) {
+                x[i] = j;
+            }
+        }
+
+        /**
+         * Return a (part) reversed copy of the data.
+         *
+         * @param x Data.
+         * @param from Start index to reverse (inclusive).
+         * @param to End index to reverse (exclusive).
+         * @return the copy
+         */
+        private static int[] reverse(int[] x, int from, int to) {
+            final int[] a = x.clone();
+            for (int i = from - 1, j = to; ++i < --j;) {
+                final int v = a[i];
+                a[i] = a[j];
+                a[j] = v;
+            }
+            return a;
+        }
+
+        /**
+         * Return a dithered copy of the data.
+         *
+         * @param x Data.
+         * @return the copy
+         */
+        private static int[] dither(int[] x) {
+            final int[] a = x.clone();
+            for (int i = a.length; --i >= 0;) {
+                // Bentley-McIlroy use i % 5.
+                // It is important this is not a power of 2 so it will not coincide
+                // with patterns created in the data using the default m powers-of-2.
+                a[i] += i % 5;
+            }
+            return a;
+        }
+
+        /**
+         * Shuffles the entries of the given array.
+         *
+         * @param rng Source of randomness.
+         * @param array Array whose entries will be shuffled (in-place).
+         * @param from Lower-bound (inclusive) of the sub-range.
+         * @param to Upper-bound (exclusive) of the sub-range.
+         */
+        private static void shuffle(UniformRandomProvider rng, int[] array, int from, int to) {
+            final int length = to - from;
+            for (int i = length; i > 1; i--) {
+                swap(array, from + i - 1, from + rng.nextInt(i));
+            }
+        }
+
+        /**
+         * Swaps the two specified elements in the array.
+         *
+         * @param array Array.
+         * @param i First index.
+         * @param j Second index.
+         */
+        private static void swap(int[] array, int i, int j) {
+            final int tmp = array[i];
+            array[i] = array[j];
+            array[j] = tmp;
+        }
+
+        /**
+         * Gets the minimum length of the data.
+         * The actual length is enumerated in {@code [length, length + range]}.
+         *
+         * @return the length
+         */
+        protected abstract int getLength();
+
+        /**
+         * Gets the range.
+         *
+         * @return the range
+         */
+        final int getRange() {
+            return range;
+        }
+    }
+
+    /**
+     * Source of {@code double} array data.
+     */
+    @State(Scope.Benchmark)
+    public static class DataSource extends AbstractDataSource {
+        /** Data length. */
+        @Param({"1000", "100000"})
+        private int length;
+
+        /** {@inheritDoc} */
+        @Override
+        protected int getLength() {
+            return length;
+        }
+    }
+
+    /**
+     * Source of quantiles.
+     */
+    @State(Scope.Benchmark)
+    public static class QuantileSource {
+        /** Quantiles.
+         * Delimited by ':' to allow use via the JMH command-line parser which
+         * uses ',' as the delimiter. */
+        @Param({"0.25:0.5:0.75",
+                "0.01:0.99",
+                "1e-100:1.0", // min,max: CM implementations do not allow p=0.0
+                "0.25:0.75",
+                "0.001:0.005:0.01:0.02:0.05:0.1:0.5",
+                "0.01:0.05:0.1:0.5:0.9:0.95:0.99"})
+        private String quantiles;
+
+        /** Data. */
+        private double[] data;
+
+        /**
+         * @return the data
+         */
+        public double[] getData() {
+            return data;
+        }
+
+        /**
+         * Create the data.
+         */
+        @Setup
+        public void setup() {
+            data = Arrays.stream(quantiles.split(":")).mapToDouble(Double::parseDouble).toArray();
+        }
+    }
+
+    /**
+     * Source of quantiles uniformly spaced within a range.
+     */
+    @State(Scope.Benchmark)
+    public static class QuantileRangeSource {
+        /** Lower quantile. */
+        @Param({"0.01"})
+        private double lowerQ;
+        /** Upper quantile. */
+        @Param({"0.99"})
+        private double upperQ;
+        /** Number of quantiles. */
+        @Param({"100"})
+        private int quantiles;
+
+        /** Data. */
+        private double[] data;
+
+        /**
+         * @return the data
+         */
+        public double[] getData() {
+            return data;
+        }
+
+        /**
+         * Create the data.
+         */
+        @Setup
+        public void setup() {
+            if (quantiles < 2) {
+                throw new IllegalStateException("Bad quantile count: " + quantiles);
+            }
+            if (!(lowerQ >= 0 && upperQ <= 1)) {
+                throw new IllegalStateException("Bad quantile range: [" + lowerQ + ", " + upperQ + "]");
+            }
+            data = new double[quantiles];
+            for (int i = 0; i < quantiles; i++) {
+                // Create u in [0, 1]
+                final double u = i / (quantiles - 1.0);
+                data[i] = (1 - u) * lowerQ + u * upperQ;
+            }
+        }
+    }
+
+    /**
+     * Source of a {@link BinaryOperator} for a {@code double[]} and quantiles.
+     */
+    @State(Scope.Benchmark)
+    public static class QuantileFunctionSource {
+        /** Name of the source. */
+        @Param({JDK, CM3, CM4, STATISTICS})
+        private String name;
+
+        /** The action. */
+        private BinaryOperator<double[]> function;
+
+        /**
+         * @return the function
+         */
+        public BinaryOperator<double[]> getFunction() {
+            return function;
+        }
+
+        /**
+         * Create the function.
+         */
+        @Setup
+        public void setup() {
+            // Note: Functions should not defensively copy the data
+            // as a clone is passed in from the data source.
+            if (JDK.equals(name)) {
+                function = QuantilePerformance::sortQuantile;
+            } else if (CM3.equals(name)) {
+                // No way to avoid a data copy here. CM does
+                // defensive copying for most array input.
+                final org.apache.commons.math3.stat.descriptive.rank.Percentile s =
+                    new org.apache.commons.math3.stat.descriptive.rank.Percentile().withNaNStrategy(
+                        org.apache.commons.math3.stat.ranking.NaNStrategy.FIXED);
+                function = (x, p) -> {
+                    final double[] q = new double[p.length];
+                    s.setData(x);
+                    for (int i = 0; i < p.length; i++) {
+                        // Convert quantile to percentile
+                        q[i] = s.evaluate(p[i] * 100);
+                    }
+                    return q;
+                };
+            } else if (CM4.equals(name)) {
+                // CM4 differs from CM3 by using Double.compare(x, y) for comparisons.
+                // This handles NaN and signed zeros but is slower than using < and >.
+                final org.apache.commons.math4.legacy.stat.descriptive.rank.Percentile s =
+                    new org.apache.commons.math4.legacy.stat.descriptive.rank.Percentile().withNaNStrategy(
+                        org.apache.commons.math4.legacy.stat.ranking.NaNStrategy.FIXED);
+                function = (x, p) -> {
+                    final double[] q = new double[p.length];
+                    s.setData(x);
+                    for (int i = 0; i < p.length; i++) {
+                        // Convert quantile to percentile
+                        q[i] = s.evaluate(p[i] * 100);
+                    }
+                    return q;
+                };
+            } else if (STATISTICS.equals(name)) {
+                function = Quantile.withDefaults()::evaluate;
+            } else {
+                throw new IllegalStateException("Unknown double[] function: " + name);
+            }
+        }
+    }
+
+    /**
+     * Sort the values and compute the median.
+     *
+     * @param values Values.
+     * @param p p-th quantiles to compute.
+     * @return the quantiles
+     */
+    static double[] sortQuantile(double[] values, double[] p) {
+        // Implicit NPE
+        final int n = values.length;
+        if (p.length == 0) {
+            throw new IllegalArgumentException("No quantiles specified");
+        }
+        for (final double pp : p) {
+            checkQuantile(pp);
+        }
+        // Special cases
+        final double[] q = new double[p.length];
+        if (n <= 1) {
+            Arrays.fill(q, n == 0 ? Double.NaN : values[0]);
+            return q;
+        }
+        // A sort is required
+        Arrays.sort(values);
+        for (int i = 0; i < p.length; i++) {
+            // EstimationMethod.HF6 (as per the Apache Commons Math Percentile
+            // legacy implementation)
+            final double pos = p[i] * (n + 1);
+            final double fpos = Math.floor(pos);
+            final int j = (int) fpos;
+            final double g = pos - fpos;
+            if (j < 1) {
+                q[i] = values[0];
+            } else if (j >= n) {
+                q[i] = values[n - 1];
+            } else {
+                q[i] = (1 - g) * values[j - 1] + g * values[j];
+            }
+        }
+        return q;
+    }
+
+    /**
+     * Check the quantile {@code p} is in the range {@code [0, 1]}.
+     *
+     * @param p Quantile.
+     * @throws IllegalArgumentException if the quantile is not in the range {@code [0, 1]}
+     */
+    private static void checkQuantile(double p) {
+        if (!(p >= 0 && p <= 1)) {
+            throw new IllegalArgumentException("Invalid quantile: " + p);
+        }
+    }
+
+    /**
+     * Create the statistic using an array and given quantiles.
+     *
+     * @param function Source of the function.
+     * @param source Source of the data.
+     * @param quantiles Source of the quantiles.
+     * @param bh Data sink.
+     */
+    @Benchmark
+    public void quantiles(QuantileFunctionSource function, DataSource source,
+            QuantileSource quantiles, Blackhole bh) {
+        final int size = source.size();
+        final double[] p = quantiles.getData();
+        final BinaryOperator<double[]> fun = function.getFunction();
+        for (int j = -1; ++j < size;) {
+            bh.consume(fun.apply(source.getData(j), p));
+        }
+    }
+
+    /**
+     * Create the statistic using an array and given quantiles.
+     *
+     * @param function Source of the function.
+     * @param source Source of the data.
+     * @param quantiles Source of the quantiles.
+     * @param bh Data sink.
+     */
+    @Benchmark
+    public void quantileRange(QuantileFunctionSource function, DataSource source,
+            QuantileRangeSource quantiles, Blackhole bh) {
+        final int size = source.size();
+        final double[] p = quantiles.getData();
+        final BinaryOperator<double[]> fun = function.getFunction();
+        for (int j = -1; ++j < size;) {
+            bh.consume(fun.apply(source.getData(j), p));
+        }
+    }
+}
diff --git a/commons-statistics-examples/examples-jmh/src/test/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformanceTest.java b/commons-statistics-examples/examples-jmh/src/test/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformanceTest.java
new file mode 100644
index 0000000..83e093f
--- /dev/null
+++ b/commons-statistics-examples/examples-jmh/src/test/java/org/apache/commons/statistics/examples/jmh/descriptive/QuantilePerformanceTest.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.commons.statistics.examples.jmh.descriptive;
+
+import java.util.EnumSet;
+import org.apache.commons.statistics.examples.jmh.descriptive.QuantilePerformance.AbstractDataSource;
+import org.apache.commons.statistics.examples.jmh.descriptive.QuantilePerformance.AbstractDataSource.Distribution;
+import org.apache.commons.statistics.examples.jmh.descriptive.QuantilePerformance.AbstractDataSource.Modification;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Executes tests for {@link QuantilePerformance}.
+ */
+class QuantilePerformanceTest {
+    @Test
+    void testGetDistribution() {
+        assertGetEnumFromParam(Distribution.class);
+    }
+
+    @Test
+    void testGetModification() {
+        assertGetEnumFromParam(Modification.class);
+    }
+
+    static <E extends Enum<E>> void assertGetEnumFromParam(Class<E> cls) {
+        Assertions.assertEquals(EnumSet.allOf(cls),
+            AbstractDataSource.getEnumFromParam(cls, "all"));
+        Assertions.assertThrows(IllegalStateException.class,
+            () -> AbstractDataSource.getEnumFromParam(cls, "nothing"));
+        for (final E e1 : cls.getEnumConstants()) {
+            final String s = e1.name().toLowerCase();
+            Assertions.assertEquals(EnumSet.of(e1),
+                AbstractDataSource.getEnumFromParam(cls, e1.name()));
+            Assertions.assertEquals(EnumSet.of(e1),
+                AbstractDataSource.getEnumFromParam(cls, s));
+            for (final E e2 : cls.getEnumConstants()) {
+                Assertions.assertEquals(EnumSet.of(e1, e2),
+                    AbstractDataSource.getEnumFromParam(cls, s + ":" + e2.name()));
+                Assertions.assertEquals(EnumSet.of(e1, e2),
+                    AbstractDataSource.getEnumFromParam(cls, e2.name() + ":" + e1.name()));
+            }
+        }
+    }
+}
diff --git a/pom.xml b/pom.xml
index f176873..892b323 100644
--- a/pom.xml
+++ b/pom.xml
@@ -139,6 +139,7 @@
     <statistics.commons.rng.version>1.5</statistics.commons.rng.version>
     <statistics.commons.numbers.version>1.2-SNAPSHOT</statistics.commons.numbers.version>
     <statistics.commons.math3.version>3.6.1</statistics.commons.math3.version>
+    <statistics.commons.math4.version>4.0-beta1</statistics.commons.math4.version>
 
     <!-- Workaround to avoid the SVN site checkout in all modules.
          This flag should be deactivated by child modules. -->
diff --git a/src/conf/pmd/pmd-ruleset.xml b/src/conf/pmd/pmd-ruleset.xml
index 87c02d0..6b83779 100644
--- a/src/conf/pmd/pmd-ruleset.xml
+++ b/src/conf/pmd/pmd-ruleset.xml
@@ -168,14 +168,15 @@
           or @SimpleName='MannWhitneyUTest' or @SimpleName='WilcoxonSignedRankTest'
           or @SimpleName='HypergeometricDistribution' or @SimpleName='UnconditionedExactTest'
           or @SimpleName='DoubleStatistics' or @SimpleName='IntStatistics'
-          or @SimpleName='LongStatistics']"/>
+          or @SimpleName='LongStatistics' or @SimpleName='Quantile']"/>
     </properties>
   </rule>
   <rule ref="category/java/design.xml/LogicInversion">
     <properties>
       <!-- Logic inversion allows detection of NaN for parameters that are expected in a range -->
       <property name="violationSuppressXPath"
-        value="./ancestor-or-self::ClassOrInterfaceDeclaration[@SimpleName='Arguments']"/>
+        value="./ancestor-or-self::ClassOrInterfaceDeclaration[@SimpleName='Arguments'
+          or @Name='Quantile']"/>
     </properties>
   </rule>
   <rule ref="category/java/design.xml/UselessOverridingMethod">
@@ -188,10 +189,11 @@
 
   <rule ref="category/java/errorprone.xml/AvoidLiteralsInIfCondition">
     <properties>
-      <!-- Add 1 as a magic number. -->
+      <!-- Add 1 as a magic number. Allow use of integer literals for counts. -->
       <property name="ignoreMagicNumbers" value="-1,0,1" />
       <property name="violationSuppressXPath"
-        value="./ancestor-or-self::MethodDeclaration[@Name='ldexp' or @Name='createMoment']"/>
+        value="./ancestor-or-self::MethodDeclaration[@Name='ldexp' or @Name='createMoment']
+          or ./ancestor-or-self::ClassOrInterfaceDeclaration[@SimpleName='Median']"/>
     </properties>
   </rule>
   <rule ref="category/java/errorprone.xml/AvoidFieldNameMatchingMethodName">
@@ -216,6 +218,12 @@
         value="./ancestor-or-self::MethodDeclaration[@Name='toBigIntegerExact']"/>
     </properties>
   </rule>
+  <rule ref="category/java/errorprone.xml/AssignmentInOperand">
+    <properties>
+      <property name="violationSuppressXPath"
+        value="./ancestor-or-self::ClassOrInterfaceDeclaration[@SimpleName='NaNTransformers']"/>
+    </properties>
+  </rule>
 
   <rule ref="category/java/performance.xml/AvoidArrayLoops">
     <properties>