Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
rnd: cosmetics to ease the implem
[simgrid.git] / src / xbt / random.cpp
1 /* Copyright (c) 2019. 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(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
42   xbt_assert(
43       min <= max,
44       "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
45   return value % range + min;
46 }
47
48 double uniform_real(double min, double max)
49 {
50   if (rng_implem == XBT_RNG_std) {
51     std::uniform_real_distribution<> dist(min, max);
52     return dist(mt19937_gen);
53     }
54
55   // This reuses Boost's uniform real distribution ideas
56   unsigned long numerator = mt19937_gen() - mt19937_gen.min();
57   unsigned long divisor   = mt19937_gen.max() - mt19937_gen.min();
58   return min + (max - min) * numerator / divisor;
59 }
60
61 double exponential(double lambda)
62 {
63   if (rng_implem == XBT_RNG_std) {
64     std::exponential_distribution<> dist(lambda);
65     return dist(mt19937_gen);
66     }
67
68   return -1 / lambda * log(uniform_real(0, 1));
69 }
70
71 double normal(double mean, double sd)
72 {
73   if (rng_implem == XBT_RNG_std) {
74     std::normal_distribution<> dist(mean, sd);
75     return dist(mt19937_gen);
76   }
77
78   double u1 = 0;
79   while (u1 < std::numeric_limits<double>::min()) {
80     u1 = uniform_real(0, 1);
81   }
82   double u2 = uniform_real(0, 1);
83   double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
84   return z0 * sd + mean;
85 }
86
87 } // namespace random
88 } // namespace xbt
89 } // namespace simgrid