Skip to content

Commit

Permalink
optimization of probability, logProbability, and cumulativeProbability
Browse files Browse the repository at this point in the history
methods in GeometricDistribution by precalculation of log(1-p) and
log(p)
  • Loading branch information
oertl committed Sep 20, 2015
1 parent 73351b6 commit 079a07f
Showing 1 changed file with 9 additions and 3 deletions.
Expand Up @@ -35,6 +35,10 @@ public class GeometricDistribution extends AbstractIntegerDistribution {
private static final long serialVersionUID = 20130507L;
/** The probability of success. */
private final double probabilityOfSuccess;
/** {@code log(p)} where p is the probability of success. */
private final double logProbabilityOfSuccess;
/** {@code log(1 - p)} where p is the probability of success. */
private final double log1mProbabilityOfSuccess;

/**
* Create a geometric distribution with the given probability of success.
Expand Down Expand Up @@ -68,6 +72,8 @@ public GeometricDistribution(RandomGenerator rng, double p) {
}

probabilityOfSuccess = p;
logProbabilityOfSuccess = FastMath.log(p);
log1mProbabilityOfSuccess = FastMath.log1p(-p);
}

/**
Expand All @@ -85,7 +91,7 @@ public double probability(int x) {
if (x < 0) {
return 0.0;
} else {
return FastMath.pow(1 - probabilityOfSuccess, x) * probabilityOfSuccess;
return FastMath.exp(log1mProbabilityOfSuccess * x) * probabilityOfSuccess;
}
}

Expand All @@ -95,7 +101,7 @@ public double logProbability(int x) {
if (x < 0) {
return Double.NEGATIVE_INFINITY;
} else {
return x * FastMath.log1p(-probabilityOfSuccess) + FastMath.log(probabilityOfSuccess);
return x * log1mProbabilityOfSuccess + logProbabilityOfSuccess;
}
}

Expand All @@ -105,7 +111,7 @@ public double cumulativeProbability(int x) {
if (x < 0) {
return 0.0;
} else {
return 1.0 - FastMath.pow(1 - probabilityOfSuccess, x + 1);
return -FastMath.expm1(log1mProbabilityOfSuccess * (x + 1));
}
}

Expand Down

0 comments on commit 079a07f

Please sign in to comment.