1 16 package org.apache.commons.math.distribution; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.math.ConvergenceException; 21 import org.apache.commons.math.FunctionEvaluationException; 22 import org.apache.commons.math.MathException; 23 import org.apache.commons.math.analysis.UnivariateRealFunction; 24 import org.apache.commons.math.analysis.UnivariateRealSolverUtils; 25 26 33 public abstract class AbstractContinuousDistribution 34 extends AbstractDistribution 35 implements ContinuousDistribution, Serializable { 36 37 38 static final long serialVersionUID = -38038050983108802L; 39 40 43 protected AbstractContinuousDistribution() { 44 super(); 45 } 46 47 58 public double inverseCumulativeProbability(final double p) 59 throws MathException { 60 if (p < 0.0 || p > 1.0) { 61 throw new IllegalArgumentException ("p must be between 0.0 and 1.0, inclusive."); 62 } 63 64 UnivariateRealFunction rootFindingFunction = 67 new UnivariateRealFunction() { 68 69 public double value(double x) throws FunctionEvaluationException { 70 try { 71 return cumulativeProbability(x) - p; 72 } catch (MathException ex) { 73 throw new FunctionEvaluationException 74 (x, "Error computing cdf", ex); 75 } 76 } 77 }; 78 79 double lowerBound = getDomainLowerBound(p); 81 double upperBound = getDomainUpperBound(p); 82 double[] bracket = null; 83 try { 84 bracket = UnivariateRealSolverUtils.bracket( 85 rootFindingFunction, getInitialDomain(p), 86 lowerBound, upperBound); 87 } catch (ConvergenceException ex) { 88 96 if (Math.abs(rootFindingFunction.value(lowerBound)) < 1E-6) { 97 return lowerBound; 98 } 99 if (Math.abs(rootFindingFunction.value(upperBound)) < 1E-6) { 100 return upperBound; 101 } 102 throw new MathException(ex); 104 } 105 106 double root = UnivariateRealSolverUtils.solve(rootFindingFunction, 108 bracket[0],bracket[1]); 109 return root; 110 } 111 112 120 protected abstract double getInitialDomain(double p); 121 122 131 protected abstract double getDomainLowerBound(double p); 132 133 142 protected abstract double getDomainUpperBound(double p); 143 } 144 | Popular Tags |