From 409d56d206891f76a3e751e4dcdcd22a8c898acc Mon Sep 17 00:00:00 2001 From: Brent Worden Date: Thu, 5 Apr 2007 15:19:57 +0000 Subject: [PATCH] MATH-153: Corrected nextInt and nextLong to handle wide value ranges. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/math/trunk@525842 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/math/random/RandomDataImpl.java | 6 ++++-- .../apache/commons/math/random/RandomDataTest.java | 12 ++++++++++++ xdocs/changes.xml | 3 +++ 3 files changed, 19 insertions(+), 2 deletions(-) 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. +