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 specified range of {@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.      * @param from Inclusive start of the range.
  153.      * @param to Exclusive end of the range.
  154.      * @return {@code Skewness} instance.
  155.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  156.      * @since 1.2
  157.      */
  158.     public static Skewness ofRange(double[] values, int from, int to) {
  159.         Statistics.checkFromToIndex(from, to, values.length);
  160.         return new Skewness(SumOfCubedDeviations.ofRange(values, from, to));
  161.     }

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

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

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

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

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

  229.     /**
  230.      * Gets the skewness of all input values.
  231.      *
  232.      * <p>When fewer than 3 values have been added, the result is {@code NaN}.
  233.      *
  234.      * @return skewness of all values.
  235.      */
  236.     @Override
  237.     public double getAsDouble() {
  238.         // This method checks the sum of squared or cubed deviations is finite
  239.         // and the value of the biased variance
  240.         // to provide a consistent result when the computation is not possible.

  241.         if (sc.n < (biased ? LENGTH_TWO : LENGTH_THREE)) {
  242.             return Double.NaN;
  243.         }
  244.         final double x2 = sc.getSumOfSquaredDeviations();
  245.         if (!Double.isFinite(x2)) {
  246.             return Double.NaN;
  247.         }
  248.         final double x3 = sc.getSumOfCubedDeviations();
  249.         if (!Double.isFinite(x3)) {
  250.             return Double.NaN;
  251.         }
  252.         // Avoid a divide by zero; for a negligible variance return NaN.
  253.         // Note: Commons Math returns zero if variance is < 1e-19.
  254.         final double m2 = x2 / sc.n;
  255.         if (Statistics.zeroVariance(sc.getFirstMoment(), m2)) {
  256.             return Double.NaN;
  257.         }
  258.         // denom = pow(m2, 1.5)
  259.         final double denom = Math.sqrt(m2) * m2;
  260.         final double m3 = x3 / sc.n;
  261.         double g1 = m3 / denom;
  262.         if (!biased) {
  263.             final double n = sc.n;
  264.             g1 *= Math.sqrt(n * (n - 1)) / (n - 2);
  265.         }
  266.         return g1;
  267.     }

  268.     @Override
  269.     public Skewness combine(Skewness other) {
  270.         sc.combine(other.sc);
  271.         return this;
  272.     }

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