1 16 package org.apache.commons.math.distribution; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.math.MathException; 21 22 23 30 public abstract class AbstractIntegerDistribution extends AbstractDistribution 31 implements IntegerDistribution, Serializable { 32 33 34 static final long serialVersionUID = -1146319659338487221L; 35 36 39 protected AbstractIntegerDistribution() { 40 super(); 41 } 42 43 58 public double cumulativeProbability(double x) throws MathException { 59 return cumulativeProbability((int) Math.floor(x)); 60 } 61 62 73 abstract public double cumulativeProbability(int x) throws MathException; 74 75 85 public double probability(double x) { 86 double fl = Math.floor(x); 87 if (fl == x) { 88 return this.probability((int) x); 89 } else { 90 return 0; 91 } 92 } 93 94 105 public double cumulativeProbability(int x0, int x1) throws MathException { 106 if (x0 > x1) { 107 throw new IllegalArgumentException 108 ("lower endpoint must be less than or equal to upper endpoint"); 109 } 110 return cumulativeProbability(x1) - cumulativeProbability(x0 - 1); 111 } 112 113 124 public int inverseCumulativeProbability(final double p) throws MathException{ 125 if (p < 0.0 || p > 1.0) { 126 throw new IllegalArgumentException ( 127 "p must be between 0 and 1.0 (inclusive)"); 128 } 129 130 int x0 = getDomainLowerBound(p); 133 int x1 = getDomainUpperBound(p); 134 double pm; 135 while (x0 < x1) { 136 int xm = x0 + (x1 - x0) / 2; 137 pm = cumulativeProbability(xm); 138 if (pm > p) { 139 if (xm == x1) { 141 --x1; 144 } else { 145 x1 = xm; 147 } 148 } else { 149 if (xm == x0) { 151 ++x0; 154 } else { 155 x0 = xm; 157 } 158 } 159 } 160 161 pm = cumulativeProbability(x0); 163 while (pm > p) { 164 --x0; 165 pm = cumulativeProbability(x0); 166 } 167 168 return x0; 169 } 170 171 180 protected abstract int getDomainLowerBound(double p); 181 182 191 protected abstract int getDomainUpperBound(double p); 192 } 193 | Popular Tags |