View Javadoc
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.math3.stat.descriptive.moment;
18  
19  import java.io.Serializable;
20  
21  import org.apache.commons.math3.exception.MathIllegalArgumentException;
22  import org.apache.commons.math3.exception.NullArgumentException;
23  import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
24  import org.apache.commons.math3.util.FastMath;
25  import org.apache.commons.math3.util.MathUtils;
26  
27  /**
28   * Computes the skewness of the available values.
29   * <p>
30   * We use the following (unbiased) formula to define skewness:</p>
31   * <p>
32   * skewness = [n / (n -1) (n - 2)] sum[(x_i - mean)^3] / std^3 </p>
33   * <p>
34   * where n is the number of values, mean is the {@link Mean} and std is the
35   * {@link StandardDeviation} </p>
36   * <p>
37   * <strong>Note that this implementation is not synchronized.</strong> If
38   * multiple threads access an instance of this class concurrently, and at least
39   * one of the threads invokes the <code>increment()</code> or
40   * <code>clear()</code> method, it must be synchronized externally. </p>
41   *
42   */
43  public class Skewness extends AbstractStorelessUnivariateStatistic implements Serializable {
44  
45      /** Serializable version identifier */
46      private static final long serialVersionUID = 7101857578996691352L;
47  
48      /** Third moment on which this statistic is based */
49      protected ThirdMoment moment = null;
50  
51       /**
52       * Determines whether or not this statistic can be incremented or cleared.
53       * <p>
54       * Statistics based on (constructed from) external moments cannot
55       * be incremented or cleared.</p>
56      */
57      protected boolean incMoment;
58  
59      /**
60       * Constructs a Skewness
61       */
62      public Skewness() {
63          incMoment = true;
64          moment = new ThirdMoment();
65      }
66  
67      /**
68       * Constructs a Skewness with an external moment
69       * @param m3 external moment
70       */
71      public Skewness(final ThirdMoment m3) {
72          incMoment = false;
73          this.moment = m3;
74      }
75  
76      /**
77       * Copy constructor, creates a new {@code Skewness} identical
78       * to the {@code original}
79       *
80       * @param original the {@code Skewness} instance to copy
81       * @throws NullArgumentException if original is null
82       */
83      public Skewness(Skewness original) throws NullArgumentException {
84          copy(original, this);
85      }
86  
87      /**
88       * {@inheritDoc}
89       * <p>Note that when {@link #Skewness(ThirdMoment)} is used to
90       * create a Skewness, this method does nothing. In that case, the
91       * ThirdMoment should be incremented directly.</p>
92       */
93      @Override
94      public void increment(final double d) {
95          if (incMoment) {
96              moment.increment(d);
97          }
98      }
99  
100     /**
101      * Returns the value of the statistic based on the values that have been added.
102      * <p>
103      * See {@link Skewness} for the definition used in the computation.</p>
104      *
105      * @return the skewness of the available values.
106      */
107     @Override
108     public double getResult() {
109 
110         if (moment.n < 3) {
111             return Double.NaN;
112         }
113         double variance = moment.m2 / (moment.n - 1);
114         if (variance < 10E-20) {
115             return 0.0d;
116         } else {
117             double n0 = moment.getN();
118             return  (n0 * moment.m3) /
119             ((n0 - 1) * (n0 -2) * FastMath.sqrt(variance) * variance);
120         }
121     }
122 
123     /**
124      * {@inheritDoc}
125      */
126     public long getN() {
127         return moment.getN();
128     }
129 
130     /**
131      * {@inheritDoc}
132      */
133     @Override
134     public void clear() {
135         if (incMoment) {
136             moment.clear();
137         }
138     }
139 
140     /**
141      * Returns the Skewness of the entries in the specifed portion of the
142      * input array.
143      * <p>
144      * See {@link Skewness} for the definition used in the computation.</p>
145      * <p>
146      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
147      *
148      * @param values the input array
149      * @param begin the index of the first array element to include
150      * @param length the number of elements to include
151      * @return the skewness of the values or Double.NaN if length is less than
152      * 3
153      * @throws MathIllegalArgumentException if the array is null or the array index
154      *  parameters are not valid
155      */
156     @Override
157     public double evaluate(final double[] values,final int begin,
158             final int length) throws MathIllegalArgumentException {
159 
160         // Initialize the skewness
161         double skew = Double.NaN;
162 
163         if (test(values, begin, length) && length > 2 ){
164             Mean mean = new Mean();
165             // Get the mean and the standard deviation
166             double m = mean.evaluate(values, begin, length);
167 
168             // Calc the std, this is implemented here instead
169             // of using the standardDeviation method eliminate
170             // a duplicate pass to get the mean
171             double accum = 0.0;
172             double accum2 = 0.0;
173             for (int i = begin; i < begin + length; i++) {
174                 final double d = values[i] - m;
175                 accum  += d * d;
176                 accum2 += d;
177             }
178             final double variance = (accum - (accum2 * accum2 / length)) / (length - 1);
179 
180             double accum3 = 0.0;
181             for (int i = begin; i < begin + length; i++) {
182                 final double d = values[i] - m;
183                 accum3 += d * d * d;
184             }
185             accum3 /= variance * FastMath.sqrt(variance);
186 
187             // Get N
188             double n0 = length;
189 
190             // Calculate skewness
191             skew = (n0 / ((n0 - 1) * (n0 - 2))) * accum3;
192         }
193         return skew;
194     }
195 
196     /**
197      * {@inheritDoc}
198      */
199     @Override
200     public Skewness copy() {
201         Skewness result = new Skewness();
202         // No try-catch or advertised exception because args are guaranteed non-null
203         copy(this, result);
204         return result;
205     }
206 
207     /**
208      * Copies source to dest.
209      * <p>Neither source nor dest can be null.</p>
210      *
211      * @param source Skewness to copy
212      * @param dest Skewness to copy to
213      * @throws NullArgumentException if either source or dest is null
214      */
215     public static void copy(Skewness source, Skewness dest)
216         throws NullArgumentException {
217         MathUtils.checkNotNull(source);
218         MathUtils.checkNotNull(dest);
219         dest.setData(source.getDataRef());
220         dest.moment = new ThirdMoment(source.moment.copy());
221         dest.incMoment = source.incMoment;
222     }
223 }