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