1 16 package org.apache.commons.math.distribution; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.math.MathException; 21 import org.apache.commons.math.special.Beta; 22 import org.apache.commons.math.util.MathUtils; 23 24 29 public class BinomialDistributionImpl 30 extends AbstractIntegerDistribution 31 implements BinomialDistribution, Serializable { 32 33 34 static final long serialVersionUID = 6751309484392813623L; 35 36 37 private int numberOfTrials; 38 39 40 private double probabilityOfSuccess; 41 42 48 public BinomialDistributionImpl(int trials, double p) { 49 super(); 50 setNumberOfTrials(trials); 51 setProbabilityOfSuccess(p); 52 } 53 54 58 public int getNumberOfTrials() { 59 return numberOfTrials; 60 } 61 62 66 public double getProbabilityOfSuccess() { 67 return probabilityOfSuccess; 68 } 69 70 76 public void setNumberOfTrials(int trials) { 77 if (trials < 0) { 78 throw new IllegalArgumentException ("number of trials must be non-negative."); 79 } 80 numberOfTrials = trials; 81 } 82 83 89 public void setProbabilityOfSuccess(double p) { 90 if (p < 0.0 || p > 1.0) { 91 throw new IllegalArgumentException ("probability of success must be between 0.0 and 1.0, inclusive."); 92 } 93 probabilityOfSuccess = p; 94 } 95 96 104 protected int getDomainLowerBound(double p) { 105 return -1; 106 } 107 108 116 protected int getDomainUpperBound(double p) { 117 return getNumberOfTrials(); 118 } 119 120 127 public double cumulativeProbability(int x) throws MathException { 128 double ret; 129 if (x < 0) { 130 ret = 0.0; 131 } else if (x >= getNumberOfTrials()) { 132 ret = 1.0; 133 } else { 134 ret = 135 1.0 - Beta.regularizedBeta( 136 getProbabilityOfSuccess(), 137 x + 1.0, 138 getNumberOfTrials() - x); 139 } 140 return ret; 141 } 142 143 149 public double probability(int x) { 150 double ret; 151 if (x < 0 || x > getNumberOfTrials()) { 152 ret = 0.0; 153 } else { 154 ret = MathUtils.binomialCoefficientDouble( 155 getNumberOfTrials(), x) * 156 Math.pow(getProbabilityOfSuccess(), x) * 157 Math.pow(1.0 - getProbabilityOfSuccess(), 158 getNumberOfTrials() - x); 159 } 160 return ret; 161 } 162 163 176 public int inverseCumulativeProbability(final double p) throws MathException { 177 if (p == 0) { 179 return -1; 180 } 181 if (p == 1) { 182 return Integer.MAX_VALUE; 183 } 184 185 return super.inverseCumulativeProbability(p); 187 } 188 } 189 | Popular Tags |