Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
7f8af6affb904c4b797b21d6b5147bcb331c3257
[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 <random>
9
10 namespace simgrid {
11 namespace xbt {
12 namespace random {
13 std::mt19937 mt19937_gen;
14
15 int uniform_int(int min, int max)
16 {
17   unsigned long gmin   = mt19937_gen.min();
18   unsigned long gmax   = mt19937_gen.max();
19   unsigned long grange = gmax - gmin + 1;
20   unsigned long range  = max - min + 1;
21   xbt_assert(range < grange || range == grange, "The current implementation of the uniform integer distribution does "
22                                                 "not allow range to be higher than mt19937's range");
23   unsigned long mult       = grange / range;
24   unsigned long maxallowed = gmin + (mult + 1) * range - 1;
25   while (true) {
26     unsigned long value = mt19937_gen();
27     if (value > maxallowed) {
28     } else {
29       return value % range + min;
30     }
31   }
32 }
33
34 double uniform_real(double min, double max)
35 {
36   // This reuses Boost's uniform real distribution ideas
37   unsigned long numerator = mt19937_gen() - mt19937_gen.min();
38   unsigned long divisor   = mt19937_gen.max() - mt19937_gen.min();
39   return min + (max - min) * numerator / divisor;
40 }
41
42 double exponential(double lambda)
43 {
44   unsigned long numerator = mt19937_gen() - mt19937_gen.min();
45   unsigned long divisor   = mt19937_gen.max() - mt19937_gen.min();
46   return -1 / lambda * log(numerator / divisor);
47 }
48
49 double normal(double mean, double sd)
50 {
51   unsigned long numeratorA = mt19937_gen() - mt19937_gen.min();
52   unsigned long numeratorB = mt19937_gen() - mt19937_gen.min();
53   unsigned long divisor    = mt19937_gen.max() - mt19937_gen.min();
54   double z0                = sqrt(-2.0 * log(numeratorA / divisor)) * cos(2 * M_PI * numeratorB / divisor);
55   return z0 * sd + mean;
56 }
57
58 } // namespace random
59 } // namespace xbt
60 } // namespace simgrid