001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.statistics.descriptive; 018 019/** 020 * Computes the skewness of the available values. The skewness is defined as: 021 * 022 * <p>\[ \gamma_1 = \operatorname{E}\left[ \left(\frac{X-\mu}{\sigma}\right)^3 \right] = \frac{\mu_3}{\sigma^3} \] 023 * 024 * <p>where \( \mu \) is the mean of \( X \), \( \sigma \) is the standard deviation of \( X \), 025 * \( \operatorname{E} \) represents the expectation operator, and \( \mu_3 \) is the third 026 * central moment. 027 * 028 * <p>The default implementation uses the following definition of the <em>sample skewness</em>: 029 * 030 * <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)}\; 031 * \frac{\tfrac{1}{n} \sum_{i=1}^n (x_i-\overline{x})^3} 032 * {\left[\tfrac{1}{n-1} \sum_{i=1}^n (x_i-\overline{x})^2 \right]^{3/2}} \] 033 * 034 * <p>where \( k_3 \) is the unique symmetric unbiased estimator of the third cumulant, 035 * \( k_2 \) is the symmetric unbiased estimator of the second cumulant (i.e. the <em>sample variance</em>), 036 * \( g_1 \) is a method of moments estimator (see below), \( \overline{x} \) is the sample mean, 037 * and \( n \) is the number of samples. 038 * 039 * <ul> 040 * <li>The result is {@code NaN} if less than 3 values are added. 041 * <li>The result is {@code NaN} if any of the values is {@code NaN} or infinite. 042 * <li>The result is {@code NaN} if the sum of the cubed deviations from the mean is infinite. 043 * </ul> 044 * 045 * <p>The default computation is for the adjusted Fisher–Pearson standardized moment coefficient 046 * \( G_1 \). If the {@link #setBiased(boolean) biased} option is enabled the following equation 047 * applies: 048 * 049 * <p>\[ g_1 = \frac{m_3}{m_2^{3/2}} = \frac{\tfrac{1}{n} \sum_{i=1}^n (x_i-\overline{x})^3} 050 * {\left[\tfrac{1}{n} \sum_{i=1}^n (x_i-\overline{x})^2 \right]^{3/2}} \] 051 * 052 * <p>where \( g_2 \) is a method of moments estimator, 053 * \( m_3 \) is the (biased) sample third central moment and \( m_2^{3/2} \) is the 054 * (biased) sample second central moment. 055 * <p>In this case the computation only requires 2 values are added (i.e. the result is 056 * {@code NaN} if less than 2 values are added). 057 * 058 * <p>Note that the computation requires division by the second central moment \( m_2 \). 059 * If this is effectively zero then the result is {@code NaN}. This occurs when the value 060 * \( m_2 \) approaches the machine precision of the mean: \( m_2 \le (m_1 \times 10^{-15})^2 \). 061 * 062 * <p>The {@link #accept(double)} method uses a recursive updating algorithm. 063 * 064 * <p>The {@link #of(double...)} method uses a two-pass algorithm, starting with computation 065 * of the mean, and then computing the sum of deviations in a second pass. 066 * 067 * <p>Note that adding values using {@link #accept(double) accept} and then executing 068 * {@link #getAsDouble() getAsDouble} will 069 * sometimes give a different result than executing 070 * {@link #of(double...) of} with the full array of values. The former approach 071 * should only be used when the full array of values is not available. 072 * 073 * <p>Supports up to 2<sup>63</sup> (exclusive) observations. 074 * This implementation does not check for overflow of the count. 075 * 076 * <p>This class is designed to work with (though does not require) 077 * {@linkplain java.util.stream streams}. 078 * 079 * <p><strong>Note that this instance is not synchronized.</strong> If 080 * multiple threads access an instance of this class concurrently, and at least 081 * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or 082 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally. 083 * 084 * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept} 085 * and {@link StatisticAccumulator#combine(StatisticResult) combine} 086 * as {@code accumulator} and {@code combiner} functions of 087 * {@link java.util.stream.Collector Collector} on a parallel stream, 088 * because the parallel instance of {@link java.util.stream.Stream#collect Stream.collect()} 089 * provides the necessary partitioning, isolation, and merging of results for 090 * safe and efficient parallel execution. 091 * 092 * @see <a href="https://en.wikipedia.org/wiki/Skewness">Skewness (Wikipedia)</a> 093 * @since 1.1 094 */ 095public final class Skewness implements DoubleStatistic, StatisticAccumulator<Skewness> { 096 /** 2, the length limit where the biased skewness is undefined. 097 * This limit effectively imposes the result m3 / m2^1.5 = 0 / 0 = NaN when 1 value 098 * has been added. Note that when more samples are added and the variance 099 * approaches zero the result is also returned as NaN. */ 100 private static final int LENGTH_TWO = 2; 101 /** 3, the length limit where the unbiased skewness is undefined. */ 102 private static final int LENGTH_THREE = 3; 103 104 /** 105 * An instance of {@link SumOfCubedDeviations}, which is used to 106 * compute the skewness. 107 */ 108 private final SumOfCubedDeviations sc; 109 110 /** Flag to control if the statistic is biased, or should use a bias correction. */ 111 private boolean biased; 112 113 /** 114 * Create an instance. 115 */ 116 private Skewness() { 117 this(new SumOfCubedDeviations()); 118 } 119 120 /** 121 * Creates an instance with the sum of cubed deviations from the mean. 122 * 123 * @param sc Sum of cubed deviations. 124 */ 125 Skewness(SumOfCubedDeviations sc) { 126 this.sc = sc; 127 } 128 129 /** 130 * Creates an instance. 131 * 132 * <p>The initial result is {@code NaN}. 133 * 134 * @return {@code Skewness} instance. 135 */ 136 public static Skewness create() { 137 return new Skewness(); 138 } 139 140 /** 141 * Returns an instance populated using the input {@code values}. 142 * 143 * <p>Note: {@code Skewness} computed using {@link #accept(double) accept} may be 144 * different from this instance. 145 * 146 * @param values Values. 147 * @return {@code Skewness} instance. 148 */ 149 public static Skewness of(double... values) { 150 return new Skewness(SumOfCubedDeviations.of(values)); 151 } 152 153 /** 154 * Returns an instance populated using the input {@code values}. 155 * 156 * <p>Note: {@code Skewness} computed using {@link #accept(double) accept} may be 157 * different from this instance. 158 * 159 * @param values Values. 160 * @return {@code Skewness} instance. 161 */ 162 public static Skewness of(int... values) { 163 return new Skewness(SumOfCubedDeviations.of(values)); 164 } 165 166 /** 167 * Returns an instance populated using the input {@code values}. 168 * 169 * <p>Note: {@code Skewness} computed using {@link #accept(double) accept} may be 170 * different from this instance. 171 * 172 * @param values Values. 173 * @return {@code Skewness} instance. 174 */ 175 public static Skewness of(long... values) { 176 return new Skewness(SumOfCubedDeviations.of(values)); 177 } 178 179 /** 180 * Updates the state of the statistic to reflect the addition of {@code value}. 181 * 182 * @param value Value. 183 */ 184 @Override 185 public void accept(double value) { 186 sc.accept(value); 187 } 188 189 /** 190 * Gets the skewness of all input values. 191 * 192 * <p>When fewer than 3 values have been added, the result is {@code NaN}. 193 * 194 * @return skewness of all values. 195 */ 196 @Override 197 public double getAsDouble() { 198 // This method checks the sum of squared or cubed deviations is finite 199 // and the value of the biased variance 200 // to provide a consistent result when the computation is not possible. 201 202 if (sc.n < (biased ? LENGTH_TWO : LENGTH_THREE)) { 203 return Double.NaN; 204 } 205 final double x2 = sc.getSumOfSquaredDeviations(); 206 if (!Double.isFinite(x2)) { 207 return Double.NaN; 208 } 209 final double x3 = sc.getSumOfCubedDeviations(); 210 if (!Double.isFinite(x3)) { 211 return Double.NaN; 212 } 213 // Avoid a divide by zero; for a negligible variance return NaN. 214 // Note: Commons Math returns zero if variance is < 1e-19. 215 final double m2 = x2 / sc.n; 216 if (Statistics.zeroVariance(sc.getFirstMoment(), m2)) { 217 return Double.NaN; 218 } 219 // denom = pow(m2, 1.5) 220 final double denom = Math.sqrt(m2) * m2; 221 final double m3 = x3 / sc.n; 222 double g1 = m3 / denom; 223 if (!biased) { 224 final double n = sc.n; 225 g1 *= Math.sqrt(n * (n - 1)) / (n - 2); 226 } 227 return g1; 228 } 229 230 @Override 231 public Skewness combine(Skewness other) { 232 sc.combine(other.sc); 233 return this; 234 } 235 236 /** 237 * Sets the value of the biased flag. The default value is {@code false}. 238 * See {@link Skewness} for details on the computing algorithm. 239 * 240 * <p>This flag only controls the final computation of the statistic. The value of this flag 241 * will not affect compatibility between instances during a {@link #combine(Skewness) combine} 242 * operation. 243 * 244 * @param v Value. 245 * @return {@code this} instance 246 */ 247 public Skewness setBiased(boolean v) { 248 biased = v; 249 return this; 250 } 251}