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.math4.legacy.stat.descriptive.moment;
18  
19  import org.apache.commons.math4.legacy.exception.MathIllegalArgumentException;
20  import org.apache.commons.math4.legacy.exception.NullArgumentException;
21  import org.apache.commons.math4.legacy.stat.descriptive.AbstractStorelessUnivariateStatistic;
22  import org.apache.commons.math4.core.jdkmath.JdkMath;
23  import org.apache.commons.math4.legacy.core.MathArrays;
24  
25  
26  /**
27   * Computes the Kurtosis of the available values.
28   * <p>
29   * We use the following (unbiased) formula to define kurtosis:</p>
30   * <p>
31   * 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)]
32   * </p><p>
33   * where n is the number of values, mean is the {@link Mean} and std is the
34   * {@link StandardDeviation}</p>
35   * <p>
36   * Note that this statistic is undefined for {@code n < 4}.  <code>Double.Nan</code>
37   * is returned when there is not sufficient data to compute the statistic.
38   * Note that Double.NaN may also be returned if the input includes NaN
39   * and / or infinite values.</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  public class Kurtosis extends AbstractStorelessUnivariateStatistic {
47      /**Fourth Moment on which this statistic is based. */
48      protected FourthMoment moment;
49  
50      /**
51       * Determines whether or not this statistic can be incremented or cleared.
52       * <p>
53       * Statistics based on (constructed from) external moments cannot
54       * be incremented or cleared.</p>
55       */
56      protected boolean incMoment;
57  
58      /**
59       * Construct a Kurtosis.
60       */
61      public Kurtosis() {
62          incMoment = true;
63          moment = new FourthMoment();
64      }
65  
66      /**
67       * Construct a Kurtosis from an external moment.
68       *
69       * @param m4 external Moment
70       */
71      public Kurtosis(final FourthMoment m4) {
72          incMoment = false;
73          this.moment = m4;
74      }
75  
76      /**
77       * Copy constructor, creates a new {@code Kurtosis} identical
78       * to the {@code original}.
79       *
80       * @param original the {@code Kurtosis} instance to copy
81       * @throws NullArgumentException if original is null
82       */
83      public Kurtosis(Kurtosis original) throws NullArgumentException {
84          copy(original, this);
85      }
86  
87      /**
88       * {@inheritDoc}
89       * <p>Note that when {@link #Kurtosis(FourthMoment)} is used to
90       * create a Variance, this method does nothing. In that case, the
91       * FourthMoment 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      * {@inheritDoc}
102      */
103     @Override
104     public double getResult() {
105         double kurtosis = Double.NaN;
106         if (moment.getN() > 3) {
107             double variance = moment.m2 / (moment.n - 1);
108                 if (moment.n <= 3 || variance < 10E-20) {
109                     kurtosis = 0.0;
110                 } else {
111                     double n = moment.n;
112                     kurtosis =
113                         (n * (n + 1) * moment.getResult() -
114                                 3 * moment.m2 * moment.m2 * (n - 1)) /
115                                 ((n - 1) * (n -2) * (n -3) * variance * variance);
116                 }
117         }
118         return kurtosis;
119     }
120 
121     /**
122      * {@inheritDoc}
123      */
124     @Override
125     public void clear() {
126         if (incMoment) {
127             moment.clear();
128         }
129     }
130 
131     /**
132      * {@inheritDoc}
133      */
134     @Override
135     public long getN() {
136         return moment.getN();
137     }
138 
139     /* UnivariateStatistic Approach  */
140 
141     /**
142      * Returns the kurtosis of the entries in the specified portion of the
143      * input array.
144      * <p>
145      * See {@link Kurtosis} for details on the computing algorithm.</p>
146      * <p>
147      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
148      *
149      * @param values the input array
150      * @param begin index of the first array element to include
151      * @param length the number of elements to include
152      * @return the kurtosis of the values or Double.NaN if length is less than 4
153      * @throws MathIllegalArgumentException if the input array is null or the array
154      * index parameters are not valid
155      */
156     @Override
157     public double evaluate(final double[] values, final int begin, final int length)
158         throws MathIllegalArgumentException {
159 
160         // Initialize the kurtosis
161         double kurt = Double.NaN;
162 
163         if (MathArrays.verifyValues(values, begin, length) && length > 3) {
164             // Compute the mean and standard deviation
165             Variance variance = new Variance();
166             variance.incrementAll(values, begin, length);
167             double mean = variance.moment.m1;
168             double stdDev = JdkMath.sqrt(variance.getResult());
169 
170             // Sum the ^4 of the distance from the mean divided by the
171             // standard deviation
172             double accum3 = 0.0;
173             for (int i = begin; i < begin + length; i++) {
174                 accum3 += JdkMath.pow(values[i] - mean, 4.0);
175             }
176             accum3 /= JdkMath.pow(stdDev, 4.0d);
177 
178             // Get N
179             double n0 = length;
180 
181             double coefficientOne =
182                 (n0 * (n0 + 1)) / ((n0 - 1) * (n0 - 2) * (n0 - 3));
183             double termTwo =
184                 (3 * JdkMath.pow(n0 - 1, 2.0)) / ((n0 - 2) * (n0 - 3));
185 
186             // Calculate kurtosis
187             kurt = (coefficientOne * accum3) - termTwo;
188         }
189         return kurt;
190     }
191 
192     /**
193      * {@inheritDoc}
194      */
195     @Override
196     public Kurtosis copy() {
197         Kurtosis result = new Kurtosis();
198         // No try-catch because args are guaranteed non-null
199         copy(this, result);
200         return result;
201     }
202 
203     /**
204      * Copies source to dest.
205      * <p>Neither source nor dest can be null.</p>
206      *
207      * @param source Kurtosis to copy
208      * @param dest Kurtosis to copy to
209      * @throws NullArgumentException if either source or dest is null
210      */
211     public static void copy(Kurtosis source, Kurtosis dest)
212         throws NullArgumentException {
213         NullArgumentException.check(source);
214         NullArgumentException.check(dest);
215         dest.moment = source.moment.copy();
216         dest.incMoment = source.incMoment;
217     }
218 }