Author: erans Date: Wed Jul 31 12:17:20 2013 New Revision: 1508829 URL: http://svn.apache.org/r1508829 Log: MATH-1011 Replaced implementation (with a more robust one, copied from "o.a.c.m.random.RandomDataGenerator").
Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math3/distribution/UniformIntegerDistribution.java Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math3/distribution/UniformIntegerDistribution.java URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math3/distribution/UniformIntegerDistribution.java?rev=1508829&r1=1508828&r2=1508829&view=diff ============================================================================== --- commons/proper/math/trunk/src/main/java/org/apache/commons/math3/distribution/UniformIntegerDistribution.java (original) +++ commons/proper/math/trunk/src/main/java/org/apache/commons/math3/distribution/UniformIntegerDistribution.java Wed Jul 31 12:17:20 2013 @@ -156,8 +156,21 @@ public class UniformIntegerDistribution /** {@inheritDoc} */ @Override public int sample() { - final double r = random.nextDouble(); - final double scaled = r * upper + (1 - r) * lower + r; - return (int) FastMath.floor(scaled); + final int max = (upper - lower) + 1; + if (max <= 0) { + // The range is too wide to fit in a positive int (larger + // than 2^31); as it covers more than half the integer range, + // we use a simple rejection method. + while (true) { + final int r = random.nextInt(); + if (r >= lower && + r <= upper) { + return r; + } + } + } else { + // We can shift the range and directly generate a positive int. + return lower + random.nextInt(max); + } } }