Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'xbt_random' into 'master'
[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 std::mt19937 mt19937_gen;
15
16 int uniform_int(int min, int max)
17 {
18   unsigned long gmin   = mt19937_gen.min();
19   unsigned long gmax   = mt19937_gen.max();
20   unsigned long grange = gmax - gmin + 1;
21   unsigned long range  = max - min + 1;
22   xbt_assert(
23       min < max || min == max,
24       "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
25   xbt_assert(range < grange || range == grange, "The current implementation of the uniform integer distribution does "
26                                                 "not allow range to be higher than mt19937's range");
27   unsigned long mult       = grange / range;
28   unsigned long maxallowed = gmin + (mult + 1) * range - 1;
29   while (true) {
30     unsigned long value = mt19937_gen();
31     if (value > maxallowed) {
32     } else {
33       return value % range + min;
34     }
35   }
36 }
37
38 double uniform_real(double min, double max)
39 {
40   // This reuses Boost's uniform real distribution ideas
41   unsigned long numerator = mt19937_gen() - mt19937_gen.min();
42   unsigned long divisor   = mt19937_gen.max() - mt19937_gen.min();
43   return min + (max - min) * numerator / divisor;
44 }
45
46 double exponential(double lambda)
47 {
48   return -1 / lambda * log(uniform_real(0, 1));
49 }
50
51 double normal(double mean, double sd)
52 {
53   double u1 = 0;
54   while (u1 < std::numeric_limits<double>::min()) {
55     u1 = uniform_real(0, 1);
56   }
57   double u2 = uniform_real(0, 1);
58   double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
59   return z0 * sd + mean;
60 }
61
62 void set_mersenne_seed(int seed)
63 {
64   mt19937_gen.seed(seed);
65 }
66
67 } // namespace random
68 } // namespace xbt
69 } // namespace simgrid