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;
16 int uniform_int(int min, int max)
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;
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;
30 unsigned long value = mt19937_gen();
31 if (value > maxallowed) {
33 return value % range + min;
38 double uniform_real(double min, double max)
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;
46 double exponential(double lambda)
48 return -1 / lambda * log(uniform_real(0, 1));
51 double normal(double mean, double sd)
54 while (u1 < std::numeric_limits<double>::min()) {
55 u1 = uniform_real(0, 1);
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;
62 void set_mersenne_seed(int seed)
64 mt19937_gen.seed(seed);
69 } // namespace simgrid