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