Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix division by zero on 32bit systems.
[simgrid.git] / src / xbt / random.cpp
1 /* Copyright (c) 2019-2020. The SimGrid Team. All rights reserved.               */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "xbt/random.hpp"
7 #include "xbt/asserts.h"
8 #include <limits>
9 #include <random>
10
11 namespace simgrid {
12 namespace xbt {
13 namespace random {
14 enum xbt_random_implem { XBT_RNG_xbt, XBT_RNG_std };
15 static xbt_random_implem rng_implem = XBT_RNG_xbt;
16
17 static std::mt19937 mt19937_gen;
18
19 void set_implem_xbt()
20 {
21   rng_implem = XBT_RNG_xbt;
22 }
23 void set_implem_std()
24 {
25   rng_implem = XBT_RNG_std;
26 }
27 void set_mersenne_seed(int seed)
28 {
29   mt19937_gen.seed(seed);
30 }
31
32 int uniform_int(int min, int max)
33 {
34   if (rng_implem == XBT_RNG_std) {
35     std::uniform_int_distribution<> dist(min, max);
36     return dist(mt19937_gen);
37   }
38
39   unsigned long range  = max - min + 1;
40   unsigned long value  = mt19937_gen();
41   xbt_assert(min <= max,
42              "The minimum value for the uniform integer distribution must not be greater than the maximum value");
43   xbt_assert(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
44   while (value >= decltype(mt19937_gen)::max() - decltype(mt19937_gen)::max() % range) {
45     value = mt19937_gen();
46   }
47   return value % range + min;
48 }
49
50 double uniform_real(double min, double max)
51 {
52   if (rng_implem == XBT_RNG_std) {
53     std::uniform_real_distribution<> dist(min, max);
54     return dist(mt19937_gen);
55   }
56
57   // This reuses Boost's uniform real distribution ideas
58   constexpr unsigned long divisor = decltype(mt19937_gen)::max() - decltype(mt19937_gen)::min();
59   unsigned long numerator;
60   do {
61     numerator = mt19937_gen() - decltype(mt19937_gen)::min();
62   } while (numerator == divisor);
63   return min + (max - min) * numerator / divisor;
64 }
65
66 double exponential(double lambda)
67 {
68   if (rng_implem == XBT_RNG_std) {
69     std::exponential_distribution<> dist(lambda);
70     return dist(mt19937_gen);
71   }
72
73   return -1.0 / lambda * log(uniform_real(0.0, 1.0));
74 }
75
76 double normal(double mean, double sd)
77 {
78   if (rng_implem == XBT_RNG_std) {
79     std::normal_distribution<> dist(mean, sd);
80     return dist(mt19937_gen);
81   }
82
83   double u1 = 0.0;
84   while (u1 < std::numeric_limits<double>::min()) {
85     u1 = uniform_real(0.0, 1.0);
86   }
87   double u2 = uniform_real(0.0, 1.0);
88   double z0 = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);
89   return z0 * sd + mean;
90 }
91
92 } // namespace random
93 } // namespace xbt
94 } // namespace simgrid