1 16 package org.apache.commons.math.stat.descriptive.rank; 17 18 import java.io.Serializable ; 19 import java.util.Arrays ; 20 import org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic; 21 22 65 public class Percentile extends AbstractUnivariateStatistic implements Serializable { 66 67 68 static final long serialVersionUID = -8091216485095130416L; 69 70 72 private double quantile = 0.0; 73 74 78 public Percentile() { 79 this(50.0); 80 } 81 82 88 public Percentile(final double p) { 89 setQuantile(p); 90 } 91 92 118 public double evaluate(final double[] values, final double p) { 119 test(values, 0, 0); 120 return evaluate(values, 0, values.length, p); 121 } 122 123 147 public double evaluate( final double[] values, final int start, final int length) { 148 return evaluate(values, start, length, quantile); 149 } 150 151 181 public double evaluate(final double[] values, final int begin, 182 final int length, final double p) { 183 184 test(values, begin, length); 185 186 if ((p > 100) || (p <= 0)) { 187 throw new IllegalArgumentException ("invalid quantile value: " + p); 188 } 189 double n = (double) length; 190 if (n == 0) { 191 return Double.NaN; 192 } 193 if (n == 1) { 194 return values[begin]; } 196 double pos = p * (n + 1) / 100; 197 double fpos = Math.floor(pos); 198 int intPos = (int) fpos; 199 double dif = pos - fpos; 200 double[] sorted = new double[length]; 201 System.arraycopy(values, begin, sorted, 0, length); 202 Arrays.sort(sorted); 203 204 if (pos < 1) { 205 return sorted[0]; 206 } 207 if (pos >= n) { 208 return sorted[length - 1]; 209 } 210 double lower = sorted[intPos - 1]; 211 double upper = sorted[intPos]; 212 return lower + dif * (upper - lower); 213 } 214 215 221 public double getQuantile() { 222 return quantile; 223 } 224 225 233 public void setQuantile(final double p) { 234 if (p <= 0 || p > 100) { 235 throw new IllegalArgumentException ("Illegal quantile value: " + p); 236 } 237 quantile = p; 238 } 239 240 } | Popular Tags |