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 unsigned long value = mt19937_gen();
44 xbt_assert(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
47 "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
48 return value % range + min;
51 double uniform_real(double min, double max)
53 switch (current_rng) {
55 return xbt_uniform_real(min, max);
57 std::uniform_real_distribution<> dist(min, max);
58 return dist(mt19937_gen);
61 xbt_assert(false, "The uniform real distribution is not yet supported for the current RNG.");
65 double xbt_uniform_real(double min, double max)
67 // This reuses Boost's uniform real distribution ideas
68 unsigned long numerator = mt19937_gen() - mt19937_gen.min();
69 unsigned long divisor = mt19937_gen.max() - mt19937_gen.min();
70 return min + (max - min) * numerator / divisor;
73 double exponential(double lambda)
75 switch (current_rng) {
77 return xbt_exponential(lambda);
79 std::exponential_distribution<> dist(lambda);
80 return dist(mt19937_gen);
83 xbt_assert(false, "The exponential distribution is not yet supported for the current RNG.");
87 double xbt_exponential(double lambda)
89 return -1 / lambda * log(uniform_real(0, 1));
92 double normal(double mean, double sd)
94 switch (current_rng) {
96 return xbt_normal(mean, sd);
98 std::normal_distribution<> dist(mean, sd);
99 return dist(mt19937_gen);
102 xbt_assert(false, "The normal distribution is not yet supported for the curent RNG.");
106 double xbt_normal(double mean, double sd)
109 while (u1 < std::numeric_limits<double>::min()) {
110 u1 = uniform_real(0, 1);
112 double u2 = uniform_real(0, 1);
113 double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
114 return z0 * sd + mean;
117 void set_mersenne_seed(int seed)
119 mt19937_gen.seed(seed);
122 } // namespace random
124 } // namespace simgrid