1 16 package org.apache.commons.math.stat.descriptive.moment; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic; 21 22 39 public class Skewness extends AbstractStorelessUnivariateStatistic implements Serializable { 40 41 42 static final long serialVersionUID = 7101857578996691352L; 43 44 45 protected ThirdMoment moment = null; 46 47 53 protected boolean incMoment; 54 55 58 public Skewness() { 59 incMoment = true; 60 moment = new ThirdMoment(); 61 } 62 63 67 public Skewness(final ThirdMoment m3) { 68 incMoment = false; 69 this.moment = m3; 70 } 71 72 75 public void increment(final double d) { 76 if (incMoment) { 77 moment.increment(d); 78 } 79 } 80 81 88 public double getResult() { 89 90 if (moment.n < 3) { 91 return Double.NaN; 92 } 93 double variance = moment.m2 / (double) (moment.n - 1); 94 double skewness = Double.NaN; 95 if (variance < 10E-20) { 96 skewness = 0.0; 97 } else { 98 double n0 = (double) moment.getN(); 99 skewness = (n0 * moment.m3) / 100 ((n0 - 1) * (n0 -2) * Math.sqrt(variance) * variance); 101 } 102 return skewness; 103 } 104 105 108 public long getN() { 109 return moment.getN(); 110 } 111 112 115 public void clear() { 116 if (incMoment) { 117 moment.clear(); 118 } 119 } 120 121 137 public double evaluate(final double[] values,final int begin, 138 final int length) { 139 140 double skew = Double.NaN; 142 143 if (test(values, begin, length) && length > 2 ){ 144 Mean mean = new Mean(); 145 double m = mean.evaluate(values, begin, length); 147 148 double accum = 0.0; 152 double accum2 = 0.0; 153 for (int i = begin; i < begin + length; i++) { 154 accum += Math.pow((values[i] - m), 2.0); 155 accum2 += (values[i] - m); 156 } 157 double stdDev = Math.sqrt((accum - (Math.pow(accum2, 2) / ((double) length))) / 158 (double) (length - 1)); 159 160 double accum3 = 0.0; 161 for (int i = begin; i < begin + length; i++) { 162 accum3 += Math.pow(values[i] - m, 3.0d); 163 } 164 accum3 /= Math.pow(stdDev, 3.0d); 165 166 double n0 = length; 168 169 skew = (n0 / ((n0 - 1) * (n0 - 2))) * accum3; 171 } 172 return skew; 173 } 174 } 175 | Popular Tags |