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"
13 std::mt19937 mt19937_gen;
15 int uniform_int(int min, int max)
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;
26 unsigned long value = mt19937_gen();
27 if (value > maxallowed) {
29 return value % range + min;
34 double uniform_real(double min, double max)
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;
42 double exponential(double lambda)
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);
49 double normal(double mean, double sd)
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;
60 } // namespace simgrid