1 /* Copyright (c) 2019. The SimGrid Team. All rights reserved. */
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. */
6 #include "xbt/random.hpp"
7 #include "xbt/asserts.h"
14 std::mt19937 mt19937_gen;
15 xbt_random_method current_rng = XBT_RNG_xbt;
19 current_rng = XBT_RNG_xbt;
23 current_rng = XBT_RNG_std;
26 int uniform_int(int min, int max)
28 switch (current_rng) {
30 return xbt_uniform_int(min, max);
32 std::uniform_int_distribution<> dist(min, max);
33 return dist(mt19937_gen);
36 xbt_assert(false, "The uniform integer distribution is not yet supported for the current RNG.");
40 int xbt_uniform_int(int min, int max)
42 unsigned long range = max - min + 1;
43 xbt_assert(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
46 "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
47 return min + (int)(range * xbt_uniform_real(0, 1));
50 double uniform_real(double min, double max)
52 switch (current_rng) {
54 return xbt_uniform_real(min, max);
56 std::uniform_real_distribution<> dist(min, max);
57 return dist(mt19937_gen);
60 xbt_assert(false, "The uniform real distribution is not yet supported for the current RNG.");
64 double xbt_uniform_real(double min, double max)
66 // This reuses Boost's uniform real distribution ideas
67 unsigned long numerator = mt19937_gen() - mt19937_gen.min();
68 unsigned long divisor = mt19937_gen.max() - mt19937_gen.min();
69 return min + (max - min) * numerator / divisor;
72 double exponential(double lambda)
74 switch (current_rng) {
76 return xbt_exponential(lambda);
78 std::exponential_distribution<> dist(lambda);
79 return dist(mt19937_gen);
82 xbt_assert(false, "The exponential distribution is not yet supported for the current RNG.");
86 double xbt_exponential(double lambda)
88 return -1 / lambda * log(uniform_real(0, 1));
91 double normal(double mean, double sd)
93 switch (current_rng) {
95 return xbt_normal(mean, sd);
97 std::normal_distribution<> dist(mean, sd);
98 return dist(mt19937_gen);
101 xbt_assert(false, "The normal distribution is not yet supported for the curent RNG.");
105 double xbt_normal(double mean, double sd)
108 while (u1 < std::numeric_limits<double>::min()) {
109 u1 = uniform_real(0, 1);
111 double u2 = uniform_real(0, 1);
112 double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
113 return z0 * sd + mean;
116 void set_mersenne_seed(int seed)
118 mt19937_gen.seed(seed);
121 } // namespace random
123 } // namespace simgrid