Kurtosis.java

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

  18. /**
  19.  * Computes the kurtosis of the available values. The kurtosis is defined as:
  20.  *
  21.  * <p>\[ \operatorname{Kurt} = \operatorname{E}\left[ \left(\frac{X-\mu}{\sigma}\right)^4 \right] = \frac{\mu_4}{\sigma^4} \]
  22.  *
  23.  * <p>where \( \mu \) is the mean of \( X \), \( \sigma \) is the standard deviation of \( X \),
  24.  * \( \operatorname{E} \) represents the expectation operator, and \( \mu_4 \) is the fourth
  25.  * central moment.
  26.  *
  27.  * <p>The default implementation uses the following definition of the <em>sample kurtosis</em>:
  28.  *
  29.  * <p>\[ G_2 = \frac{k_4}{k_2^2} = \;
  30.  *       \frac{n-1}{(n-2)\,(n-3)} \left[(n+1)\,\frac{m_4}{m_{2}^2} - 3\,(n-1) \right] \]
  31.  *
  32.  * <p>where \( k_4 \) is the unique symmetric unbiased estimator of the fourth cumulant,
  33.  * \( k_2 \) is the symmetric unbiased estimator of the second cumulant (i.e. the <em>sample variance</em>),
  34.  * \( m_4 \) is the fourth sample moment about the mean,
  35.  * \( m_2 \) is the second sample moment about the mean,
  36.  * \( \overline{x} \) is the sample mean,
  37.  * and \( n \) is the number of samples.
  38.  *
  39.  * <ul>
  40.  *   <li>The result is {@code NaN} if less than 4 values are added.
  41.  *   <li>The result is {@code NaN} if any of the values is {@code NaN} or infinite.
  42.  *   <li>The result is {@code NaN} if the sum of the fourth deviations from the mean is infinite.
  43.  * </ul>
  44.  *
  45.  * <p>The default computation is for the adjusted Fisher–Pearson standardized moment coefficient
  46.  * \( G_2 \). If the {@link #setBiased(boolean) biased} option is enabled the following equation
  47.  * applies:
  48.  *
  49.  * <p>\[ g_2 = \frac{m_4}{m_2^2} - 3 = \frac{\tfrac{1}{n} \sum_{i=1}^n (x_i-\overline{x})^4}
  50.  *            {\left[\tfrac{1}{n} \sum_{i=1}^n (x_i-\overline{x})^2 \right]^2} - 3 \]
  51.  *
  52.  * <p>In this case the computation only requires 2 values are added (i.e. the result is
  53.  * {@code NaN} if less than 2 values are added).
  54.  *
  55.  * <p>Note that the computation requires division by the second central moment \( m_2 \).
  56.  * If this is effectively zero then the result is {@code NaN}. This occurs when the value
  57.  * \( m_2 \) approaches the machine precision of the mean: \( m_2 \le (m_1 \times 10^{-15})^2 \).
  58.  *
  59.  * <p>The {@link #accept(double)} method uses a recursive updating algorithm.
  60.  *
  61.  * <p>The {@link #of(double...)} method uses a two-pass algorithm, starting with computation
  62.  * of the mean, and then computing the sum of deviations in a second pass.
  63.  *
  64.  * <p>Note that adding values using {@link #accept(double) accept} and then executing
  65.  * {@link #getAsDouble() getAsDouble} will
  66.  * sometimes give a different result than executing
  67.  * {@link #of(double...) of} with the full array of values. The former approach
  68.  * should only be used when the full array of values is not available.
  69.  *
  70.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  71.  * This implementation does not check for overflow of the count.
  72.  *
  73.  * <p>This class is designed to work with (though does not require)
  74.  * {@linkplain java.util.stream streams}.
  75.  *
  76.  * <p><strong>Note that this instance is not synchronized.</strong> If
  77.  * multiple threads access an instance of this class concurrently, and at least
  78.  * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
  79.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  80.  *
  81.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  82.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  83.  * as {@code accumulator} and {@code combiner} functions of
  84.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  85.  * because the parallel instance of {@link java.util.stream.Stream#collect Stream.collect()}
  86.  * provides the necessary partitioning, isolation, and merging of results for
  87.  * safe and efficient parallel execution.
  88.  *
  89.  * @see <a href="https://en.wikipedia.org/wiki/Kurtosis">Kurtosis (Wikipedia)</a>
  90.  * @since 1.1
  91.  */
  92. public final class Kurtosis implements DoubleStatistic, StatisticAccumulator<Kurtosis> {
  93.     /** 2, the length limit where the biased skewness is undefined.
  94.      * This limit effectively imposes the result m4 / m2^2 = 0 / 0 = NaN when 1 value
  95.      * has been added. Note that when more samples are added and the variance
  96.      * approaches zero the result is also returned as NaN. */
  97.     private static final int LENGTH_TWO = 2;
  98.     /** 4, the length limit where the kurtosis is undefined. */
  99.     private static final int LENGTH_FOUR = 4;

  100.     /**
  101.      * An instance of {@link SumOfFourthDeviations}, which is used to
  102.      * compute the kurtosis.
  103.      */
  104.     private final SumOfFourthDeviations sq;

  105.     /** Flag to control if the statistic is biased, or should use a bias correction. */
  106.     private boolean biased;

  107.     /**
  108.      * Create an instance.
  109.      */
  110.     private Kurtosis() {
  111.         this(new SumOfFourthDeviations());
  112.     }

  113.     /**
  114.      * Creates an instance with the sum of fourth deviations from the mean.
  115.      *
  116.      * @param sq Sum of fourth deviations.
  117.      */
  118.     Kurtosis(SumOfFourthDeviations sq) {
  119.         this.sq = sq;
  120.     }

  121.     /**
  122.      * Creates an instance.
  123.      *
  124.      * <p>The initial result is {@code NaN}.
  125.      *
  126.      * @return {@code Kurtosis} instance.
  127.      */
  128.     public static Kurtosis create() {
  129.         return new Kurtosis();
  130.     }

  131.     /**
  132.      * Returns an instance populated using the input {@code values}.
  133.      *
  134.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  135.      * different from this instance.
  136.      *
  137.      * @param values Values.
  138.      * @return {@code Kurtosis} instance.
  139.      */
  140.     public static Kurtosis of(double... values) {
  141.         return new Kurtosis(SumOfFourthDeviations.of(values));
  142.     }

  143.     /**
  144.      * Returns an instance populated using the specified range of {@code values}.
  145.      *
  146.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  147.      * different from this instance.
  148.      *
  149.      * @param values Values.
  150.      * @param from Inclusive start of the range.
  151.      * @param to Exclusive end of the range.
  152.      * @return {@code Kurtosis} instance.
  153.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  154.      * @since 1.2
  155.      */
  156.     public static Kurtosis ofRange(double[] values, int from, int to) {
  157.         Statistics.checkFromToIndex(from, to, values.length);
  158.         return new Kurtosis(SumOfFourthDeviations.ofRange(values, from, to));
  159.     }

  160.     /**
  161.      * Returns an instance populated using the input {@code values}.
  162.      *
  163.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  164.      * different from this instance.
  165.      *
  166.      * @param values Values.
  167.      * @return {@code Kurtosis} instance.
  168.      */
  169.     public static Kurtosis of(int... values) {
  170.         return new Kurtosis(SumOfFourthDeviations.of(values));
  171.     }

  172.     /**
  173.      * Returns an instance populated using the specified range of {@code values}.
  174.      *
  175.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  176.      * different from this instance.
  177.      *
  178.      * @param values Values.
  179.      * @param from Inclusive start of the range.
  180.      * @param to Exclusive end of the range.
  181.      * @return {@code Kurtosis} instance.
  182.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  183.      * @since 1.2
  184.      */
  185.     public static Kurtosis ofRange(int[] values, int from, int to) {
  186.         Statistics.checkFromToIndex(from, to, values.length);
  187.         return new Kurtosis(SumOfFourthDeviations.ofRange(values, from, to));
  188.     }

  189.     /**
  190.      * Returns an instance populated using the input {@code values}.
  191.      *
  192.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  193.      * different from this instance.
  194.      *
  195.      * @param values Values.
  196.      * @return {@code Kurtosis} instance.
  197.      */
  198.     public static Kurtosis of(long... values) {
  199.         return new Kurtosis(SumOfFourthDeviations.of(values));
  200.     }

  201.     /**
  202.      * Returns an instance populated using the specified range of {@code values}.
  203.      *
  204.      * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
  205.      * different from this instance.
  206.      *
  207.      * @param values Values.
  208.      * @param from Inclusive start of the range.
  209.      * @param to Exclusive end of the range.
  210.      * @return {@code Kurtosis} instance.
  211.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  212.      * @since 1.2
  213.      */
  214.     public static Kurtosis ofRange(long[] values, int from, int to) {
  215.         Statistics.checkFromToIndex(from, to, values.length);
  216.         return new Kurtosis(SumOfFourthDeviations.ofRange(values, from, to));
  217.     }

  218.     /**
  219.      * Updates the state of the statistic to reflect the addition of {@code value}.
  220.      *
  221.      * @param value Value.
  222.      */
  223.     @Override
  224.     public void accept(double value) {
  225.         sq.accept(value);
  226.     }

  227.     /**
  228.      * Gets the kurtosis of all input values.
  229.      *
  230.      * <p>When fewer than 4 values have been added, the result is {@code NaN}.
  231.      *
  232.      * @return kurtosis of all values.
  233.      */
  234.     @Override
  235.     public double getAsDouble() {
  236.         // This method checks the sum of squared or fourth deviations is finite
  237.         // to provide a consistent NaN when the computation is not possible.

  238.         if (sq.n < (biased ? LENGTH_TWO : LENGTH_FOUR)) {
  239.             return Double.NaN;
  240.         }
  241.         final double x2 = sq.getSumOfSquaredDeviations();
  242.         if (!Double.isFinite(x2)) {
  243.             return Double.NaN;
  244.         }
  245.         final double x4 = sq.getSumOfFourthDeviations();
  246.         if (!Double.isFinite(x4)) {
  247.             return Double.NaN;
  248.         }
  249.         // Avoid a divide by zero; for a negligible variance return NaN.
  250.         // Note: Commons Math returns zero if variance is < 1e-19.
  251.         final double m2 = x2 / sq.n;
  252.         if (Statistics.zeroVariance(sq.getFirstMoment(), m2)) {
  253.             return Double.NaN;
  254.         }
  255.         final double m4 = x4 / sq.n;
  256.         if (biased) {
  257.             return m4 / (m2 * m2) - 3;
  258.         }
  259.         final double n = sq.n;
  260.         return ((n * n - 1) * m4 / (m2 * m2) - 3 * (n - 1) * (n - 1)) / ((n - 2) * (n - 3));
  261.     }

  262.     @Override
  263.     public Kurtosis combine(Kurtosis other) {
  264.         sq.combine(other.sq);
  265.         return this;
  266.     }

  267.     /**
  268.      * Sets the value of the biased flag. The default value is {@code false}.
  269.      * See {@link Kurtosis} for details on the computing algorithm.
  270.      *
  271.      * <p>This flag only controls the final computation of the statistic. The value of this flag
  272.      * will not affect compatibility between instances during a {@link #combine(Kurtosis) combine}
  273.      * operation.
  274.      *
  275.      * @param v Value.
  276.      * @return {@code this} instance
  277.      */
  278.     public Kurtosis setBiased(boolean v) {
  279.         biased = v;
  280.         return this;
  281.     }
  282. }