diff --git a/src/java/org/apache/commons/math/random/RandomDataImpl.java b/src/java/org/apache/commons/math/random/RandomDataImpl.java index ef3b6a352..a56abecd5 100644 --- a/src/java/org/apache/commons/math/random/RandomDataImpl.java +++ b/src/java/org/apache/commons/math/random/RandomDataImpl.java @@ -167,7 +167,8 @@ public class RandomDataImpl implements RandomData, Serializable { ("upper bound must be > lower bound"); } RandomGenerator rand = getRan(); - return lower + (int) (rand.nextDouble() * (upper - lower + 1)); + double r = rand.nextDouble(); + return (int)((r * upper) + ((1.0 - r) * lower) + r); } /** @@ -184,7 +185,8 @@ public class RandomDataImpl implements RandomData, Serializable { ("upper bound must be > lower bound"); } RandomGenerator rand = getRan(); - return lower + (long) (rand.nextDouble() * (upper - lower + 1)); + double r = rand.nextDouble(); + return (long)((r * upper) + ((1.0 - r) * lower) + r); } /** diff --git a/src/test/org/apache/commons/math/random/RandomDataTest.java b/src/test/org/apache/commons/math/random/RandomDataTest.java index a2354e34e..d2b0559dc 100644 --- a/src/test/org/apache/commons/math/random/RandomDataTest.java +++ b/src/test/org/apache/commons/math/random/RandomDataTest.java @@ -58,6 +58,18 @@ public class RandomDataTest extends RetryTestCase { return suite; } + public void testNextIntExtremeValues() { + int x = randomData.nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE); + int y = randomData.nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE); + assertFalse(x == y); + } + + public void testNextLongExtremeValues() { + long x = randomData.nextLong(Long.MIN_VALUE, Long.MAX_VALUE); + long y = randomData.nextLong(Long.MIN_VALUE, Long.MAX_VALUE); + assertFalse(x == y); + } + /** test dispersion and failure modes for nextInt() */ public void testNextInt() { try { diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 22cf98067..2739c536d 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -71,6 +71,9 @@ Commons Math Release Notes Modified getSumSquaredErrors method in SimpleRegression to always return a non-negative result. + + Corrected nextInt and nextLong to handle wide value ranges. +