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

  102.     /**
  103.      * An instance of {@link SumOfCubedDeviations}, which is used to
  104.      * compute the skewness.
  105.      */
  106.     private final SumOfCubedDeviations sc;

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

  109.     /**
  110.      * Create an instance.
  111.      */
  112.     private Skewness() {
  113.         this(new SumOfCubedDeviations());
  114.     }

  115.     /**
  116.      * Creates an instance with the sum of cubed deviations from the mean.
  117.      *
  118.      * @param sc Sum of cubed deviations.
  119.      */
  120.     Skewness(SumOfCubedDeviations sc) {
  121.         this.sc = sc;
  122.     }

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

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

  145.     /**
  146.      * Returns an instance populated using the input {@code values}.
  147.      *
  148.      * <p>Note: {@code Skewness} computed using {@link #accept(double) accept} may be
  149.      * different from this instance.
  150.      *
  151.      * @param values Values.
  152.      * @return {@code Skewness} instance.
  153.      */
  154.     public static Skewness of(int... values) {
  155.         return new Skewness(SumOfCubedDeviations.of(values));
  156.     }

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

  169.     /**
  170.      * Updates the state of the statistic to reflect the addition of {@code value}.
  171.      *
  172.      * @param value Value.
  173.      */
  174.     @Override
  175.     public void accept(double value) {
  176.         sc.accept(value);
  177.     }

  178.     /**
  179.      * Gets the skewness of all input values.
  180.      *
  181.      * <p>When fewer than 3 values have been added, the result is {@code NaN}.
  182.      *
  183.      * @return skewness of all values.
  184.      */
  185.     @Override
  186.     public double getAsDouble() {
  187.         // This method checks the sum of squared or cubed deviations is finite
  188.         // and the value of the biased variance
  189.         // to provide a consistent result when the computation is not possible.

  190.         if (sc.n < (biased ? LENGTH_TWO : LENGTH_THREE)) {
  191.             return Double.NaN;
  192.         }
  193.         final double x2 = sc.getSumOfSquaredDeviations();
  194.         if (!Double.isFinite(x2)) {
  195.             return Double.NaN;
  196.         }
  197.         final double x3 = sc.getSumOfCubedDeviations();
  198.         if (!Double.isFinite(x3)) {
  199.             return Double.NaN;
  200.         }
  201.         // Avoid a divide by zero; for a negligible variance return NaN.
  202.         // Note: Commons Math returns zero if variance is < 1e-19.
  203.         final double m2 = x2 / sc.n;
  204.         if (Statistics.zeroVariance(sc.getFirstMoment(), m2)) {
  205.             return Double.NaN;
  206.         }
  207.         // denom = pow(m2, 1.5)
  208.         final double denom = Math.sqrt(m2) * m2;
  209.         final double m3 = x3 / sc.n;
  210.         double g1 = m3 / denom;
  211.         if (!biased) {
  212.             final double n = sc.n;
  213.             g1 *= Math.sqrt(n * (n - 1)) / (n - 2);
  214.         }
  215.         return g1;
  216.     }

  217.     @Override
  218.     public Skewness combine(Skewness other) {
  219.         sc.combine(other.sc);
  220.         return this;
  221.     }

  222.     /**
  223.      * Sets the value of the biased flag. The default value is {@code false}.
  224.      * See {@link Skewness} for details on the computing algorithm.
  225.      *
  226.      * <p>This flag only controls the final computation of the statistic. The value of this flag
  227.      * will not affect compatibility between instances during a {@link #combine(Skewness) combine}
  228.      * operation.
  229.      *
  230.      * @param v Value.
  231.      * @return {@code this} instance
  232.      */
  233.     public Skewness setBiased(boolean v) {
  234.         biased = v;
  235.         return this;
  236.     }
  237. }