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