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 enum xbt_random_implem { XBT_RNG_xbt, XBT_RNG_std };
15 static xbt_random_implem rng_implem = XBT_RNG_xbt;
17 static std::mt19937 mt19937_gen;
21 rng_implem = XBT_RNG_xbt;
25 rng_implem = XBT_RNG_std;
27 void set_mersenne_seed(int seed)
29 mt19937_gen.seed(seed);
32 int uniform_int(int min, int max)
34 if (rng_implem == XBT_RNG_std) {
35 std::uniform_int_distribution<> dist(min, max);
36 return dist(mt19937_gen);
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.");
44 "The maximum value for the uniform integer distribution must be greater than or equal to the minimum value");
45 return value % range + min;
48 double uniform_real(double min, double max)
50 if (rng_implem == XBT_RNG_std) {
51 std::uniform_real_distribution<> dist(min, max);
52 return dist(mt19937_gen);
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;
61 double exponential(double lambda)
63 if (rng_implem == XBT_RNG_std) {
64 std::exponential_distribution<> dist(lambda);
65 return dist(mt19937_gen);
68 return -1 / lambda * log(uniform_real(0, 1));
71 double normal(double mean, double sd)
73 if (rng_implem == XBT_RNG_std) {
74 std::normal_distribution<> dist(mean, sd);
75 return dist(mt19937_gen);
79 while (u1 < std::numeric_limits<double>::min()) {
80 u1 = uniform_real(0, 1);
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;
89 } // namespace simgrid