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.math4.legacy.stat.descriptive.moment;

  18. import org.apache.commons.math4.legacy.exception.MathIllegalArgumentException;
  19. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  20. import org.apache.commons.math4.legacy.stat.descriptive.AbstractStorelessUnivariateStatistic;
  21. import org.apache.commons.math4.core.jdkmath.JdkMath;
  22. import org.apache.commons.math4.legacy.core.MathArrays;

  23. /**
  24.  * Computes the skewness of the available values.
  25.  * <p>
  26.  * We use the following (unbiased) formula to define skewness:</p>
  27.  * <p>
  28.  * skewness = [n / (n -1) (n - 2)] sum[(x_i - mean)^3] / std^3 </p>
  29.  * <p>
  30.  * where n is the number of values, mean is the {@link Mean} and std is the
  31.  * {@link StandardDeviation} </p>
  32.  * <p>
  33.  * Note that this statistic is undefined for {@code n < 3}.  <code>Double.Nan</code>
  34.  * is returned when there is not sufficient data to compute the statistic.
  35.  * Double.NaN may also be returned if the input includes NaN and / or
  36.  * infinite values.</p>
  37.  * <p>
  38.  * <strong>Note that this implementation is not synchronized.</strong> If
  39.  * multiple threads access an instance of this class concurrently, and at least
  40.  * one of the threads invokes the <code>increment()</code> or
  41.  * <code>clear()</code> method, it must be synchronized externally. </p>
  42.  */
  43. public class Skewness extends AbstractStorelessUnivariateStatistic {
  44.     /** The value below which the variance is considered zero and thus skewness is zero. */
  45.     private static final double ZERO_VARIANCE_THRESHOLD = 10E-20;

  46.     /** Third moment on which this statistic is based. */
  47.     protected ThirdMoment moment;

  48.      /**
  49.      * Determines whether or not this statistic can be incremented or cleared.
  50.      * <p>
  51.      * Statistics based on (constructed from) external moments cannot
  52.      * be incremented or cleared.</p>
  53.     */
  54.     protected boolean incMoment;

  55.     /**
  56.      * Constructs a Skewness.
  57.      */
  58.     public Skewness() {
  59.         incMoment = true;
  60.         moment = new ThirdMoment();
  61.     }

  62.     /**
  63.      * Constructs a Skewness with an external moment.
  64.      * @param m3 external moment
  65.      */
  66.     public Skewness(final ThirdMoment m3) {
  67.         incMoment = false;
  68.         this.moment = m3;
  69.     }

  70.     /**
  71.      * Copy constructor, creates a new {@code Skewness} identical
  72.      * to the {@code original}.
  73.      *
  74.      * @param original the {@code Skewness} instance to copy
  75.      * @throws NullArgumentException if original is null
  76.      */
  77.     public Skewness(Skewness original) throws NullArgumentException {
  78.         copy(original, this);
  79.     }

  80.     /**
  81.      * {@inheritDoc}
  82.      * <p>Note that when {@link #Skewness(ThirdMoment)} is used to
  83.      * create a Skewness, this method does nothing. In that case, the
  84.      * ThirdMoment should be incremented directly.</p>
  85.      */
  86.     @Override
  87.     public void increment(final double d) {
  88.         if (incMoment) {
  89.             moment.increment(d);
  90.         }
  91.     }

  92.     /**
  93.      * Returns the value of the statistic based on the values that have been added.
  94.      * <p>
  95.      * See {@link Skewness} for the definition used in the computation.</p>
  96.      *
  97.      * @return the skewness of the available values.
  98.      */
  99.     @Override
  100.     public double getResult() {

  101.         if (moment.n < 3) {
  102.             return Double.NaN;
  103.         }
  104.         double variance = moment.m2 / (moment.n - 1);
  105.         if (variance < ZERO_VARIANCE_THRESHOLD) {
  106.             return 0.0d;
  107.         } else {
  108.             double n0 = moment.getN();
  109.             return  (n0 * moment.m3) /
  110.             ((n0 - 1) * (n0 -2) * JdkMath.sqrt(variance) * variance);
  111.         }
  112.     }

  113.     /**
  114.      * {@inheritDoc}
  115.      */
  116.     @Override
  117.     public long getN() {
  118.         return moment.getN();
  119.     }

  120.     /**
  121.      * {@inheritDoc}
  122.      */
  123.     @Override
  124.     public void clear() {
  125.         if (incMoment) {
  126.             moment.clear();
  127.         }
  128.     }

  129.     /**
  130.      * Returns the Skewness of the entries in the specified portion of the
  131.      * input array.
  132.      * <p>
  133.      * See {@link Skewness} for the definition used in the computation.</p>
  134.      * <p>
  135.      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
  136.      *
  137.      * @param values the input array
  138.      * @param begin the index of the first array element to include
  139.      * @param length the number of elements to include
  140.      * @return the skewness of the values or Double.NaN if length is less than 3
  141.      * @throws MathIllegalArgumentException if the array is null or the array index
  142.      *  parameters are not valid
  143.      */
  144.     @Override
  145.     public double evaluate(final double[] values,final int begin, final int length)
  146.         throws MathIllegalArgumentException {

  147.         // Initialize the skewness
  148.         double skew = Double.NaN;

  149.         if (MathArrays.verifyValues(values, begin, length) && length > 2 ) {
  150.             Mean mean = new Mean();
  151.             // Get the mean and the standard deviation
  152.             double m = mean.evaluate(values, begin, length);

  153.             // Calc the std, this is implemented here instead
  154.             // of using the standardDeviation method eliminate
  155.             // a duplicate pass to get the mean
  156.             double accum = 0.0;
  157.             double accum2 = 0.0;
  158.             for (int i = begin; i < begin + length; i++) {
  159.                 final double d = values[i] - m;
  160.                 accum  += d * d;
  161.                 accum2 += d;
  162.             }
  163.             final double variance = (accum - (accum2 * accum2 / length)) / (length - 1);
  164.             if (variance < ZERO_VARIANCE_THRESHOLD) {
  165.                 skew = 0.0d;
  166.             } else {
  167.                 double accum3 = 0.0;
  168.                 for (int i = begin; i < begin + length; i++) {
  169.                     final double d = values[i] - m;
  170.                     accum3 += d * d * d;
  171.                 }
  172.                 accum3 /= variance * JdkMath.sqrt(variance);

  173.                 // Get N
  174.                 double n0 = length;

  175.                 // Calculate skewness
  176.                 skew = (n0 / ((n0 - 1) * (n0 - 2))) * accum3;
  177.             }
  178.         }
  179.         return skew;
  180.     }

  181.     /**
  182.      * {@inheritDoc}
  183.      */
  184.     @Override
  185.     public Skewness copy() {
  186.         Skewness result = new Skewness();
  187.         // No try-catch or advertised exception because args are guaranteed non-null
  188.         copy(this, result);
  189.         return result;
  190.     }

  191.     /**
  192.      * Copies source to dest.
  193.      * <p>Neither source nor dest can be null.</p>
  194.      *
  195.      * @param source Skewness to copy
  196.      * @param dest Skewness to copy to
  197.      * @throws NullArgumentException if either source or dest is null
  198.      */
  199.     public static void copy(Skewness source, Skewness dest)
  200.         throws NullArgumentException {
  201.         NullArgumentException.check(source);
  202.         NullArgumentException.check(dest);
  203.         dest.moment = new ThirdMoment(source.moment.copy());
  204.         dest.incMoment = source.incMoment;
  205.     }
  206. }