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