This is an automated email from the ASF dual-hosted git repository. aherbert pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-statistics.git
commit 494b551113cee9b8c9a2bd1b333d09dfe8ef53ce Author: aherbert <[email protected]> AuthorDate: Mon Sep 27 12:31:39 2021 +0100 Simplify midpoint computation in AbstractDiscreteDistribution Use of long variables avoids checks for overflow. Closes #2 --- .../distribution/AbstractDiscreteDistribution.java | 28 ++++++++++------------ 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java index 351c951..5a01262 100644 --- a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java +++ b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java @@ -103,27 +103,23 @@ abstract class AbstractDiscreteDistribution private int solveInverseCumulativeProbability(final double p, int lowerBound, int upperBound) { - int lower = lowerBound; - int upper = upperBound; + // Use long to prevent overflow during computation of the middle + long lower = lowerBound; + long upper = upperBound; while (lower + 1 < upper) { - int xm = (lower + upper) / 2; - if (xm < lower || xm > upper) { - /* - * Overflow. - * There will never be an overflow in both calculation methods - * for xm at the same time - */ - xm = lower + (upper - lower) / 2; - } - - final double pm = checkedCumulativeProbability(xm); + // Cannot replace division by 2 with a right shift because (lower + upper) + // can be negative. This can be optimized when we know that both + // lower and upper arguments of this method are positive, for + // example, for PoissonDistribution. + final long middle = (lower + upper) / 2; + final double pm = checkedCumulativeProbability((int) middle); if (pm >= p) { - upper = xm; + upper = middle; } else { - lower = xm; + lower = middle; } } - return upper; + return (int) upper; } /**
