Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Modifying how uniform integer are generated
authorYann Duplouy <yann.duplouy@inria.fr>
Wed, 20 Nov 2019 10:25:16 +0000 (11:25 +0100)
committerYann Duplouy <yann.duplouy@inria.fr>
Wed, 20 Nov 2019 10:25:16 +0000 (11:25 +0100)
src/xbt/random.cpp
src/xbt/random_test.cpp

index 7045649..449782a 100644 (file)
@@ -39,24 +39,12 @@ int uniform_int(int min, int max)
 
 int xbt_uniform_int(int min, int max)
 {
 
 int xbt_uniform_int(int min, int max)
 {
-  unsigned long gmin   = mt19937_gen.min();
-  unsigned long gmax   = mt19937_gen.max();
-  unsigned long grange = gmax - gmin + 1;
   unsigned long range  = max - min + 1;
   unsigned long range  = max - min + 1;
+  xbt_assert(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
   xbt_assert(
       min <= max,
       "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
   xbt_assert(
       min <= max,
       "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
-  xbt_assert(range <= grange, "The current implementation of the uniform integer distribution does not allow range to "
-                              "be higher than mt19937's range");
-  unsigned long mult       = grange / range;
-  unsigned long maxallowed = gmin + (mult + 1) * range - 1;
-  while (true) {
-    unsigned long value = mt19937_gen();
-    if (value > maxallowed) {
-    } else {
-      return value % range + min;
-    }
-  }
+  return min + (int)(range * xbt_uniform_real(0, 1));
 }
 
 double uniform_real(double min, double max)
 }
 
 double uniform_real(double min, double max)
index c93049b..faffe9d 100644 (file)
@@ -14,7 +14,7 @@ TEST_CASE("xbt::random: Random Number Generation")
     simgrid::xbt::random::set_mersenne_seed(12345);
 
     REQUIRE(simgrid::xbt::random::exponential(25) == 0.00291934351538427348);
     simgrid::xbt::random::set_mersenne_seed(12345);
 
     REQUIRE(simgrid::xbt::random::exponential(25) == 0.00291934351538427348);
-    REQUIRE(simgrid::xbt::random::uniform_int(1, 6) == 4);
+    REQUIRE(simgrid::xbt::random::uniform_int(1, 6) == 6);
     REQUIRE(simgrid::xbt::random::uniform_real(0, 1) == 0.31637556043369124970);
     REQUIRE(simgrid::xbt::random::normal(0, 2) == 1.62746784745133976635);
   }
     REQUIRE(simgrid::xbt::random::uniform_real(0, 1) == 0.31637556043369124970);
     REQUIRE(simgrid::xbt::random::normal(0, 2) == 1.62746784745133976635);
   }