1 /* Copyright (c) 2019-2020. 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"
15 int StdRandom::uniform_int(int min, int max)
17 std::uniform_int_distribution<> dist(min, max);
18 return dist(mt19937_gen);
21 double StdRandom::uniform_real(double min, double max)
23 std::uniform_real_distribution<> dist(min, max);
24 return dist(mt19937_gen);
27 double StdRandom::exponential(double lambda)
29 std::exponential_distribution<> dist(lambda);
30 return dist(mt19937_gen);
33 double StdRandom::normal(double mean, double sd)
35 std::normal_distribution<> dist(mean, sd);
36 return dist(mt19937_gen);
39 int XbtRandom::uniform_int(int min, int max)
41 unsigned long range = max - min + 1;
42 xbt_assert(min <= max,
43 "The minimum value for the uniform integer distribution must not be greater than the maximum value");
44 xbt_assert(range > 0, "Overflow in the uniform integer distribution, please use a smaller range.");
47 value = mt19937_gen();
48 } while (value >= decltype(mt19937_gen)::max() - decltype(mt19937_gen)::max() % range);
49 return value % range + min;
52 double XbtRandom::uniform_real(double min, double max)
54 // This reuses Boost's uniform real distribution ideas
55 constexpr unsigned long divisor = decltype(mt19937_gen)::max() - decltype(mt19937_gen)::min();
56 unsigned long numerator;
58 numerator = mt19937_gen() - decltype(mt19937_gen)::min();
59 } while (numerator == divisor);
60 return min + (max - min) * numerator / divisor;
63 double XbtRandom::exponential(double lambda)
65 return -1.0 / lambda * log(uniform_real(0.0, 1.0));
68 double XbtRandom::normal(double mean, double sd)
72 u1 = uniform_real(0.0, 1.0);
73 } while (u1 < std::numeric_limits<double>::min());
74 double u2 = uniform_real(0.0, 1.0);
75 double z0 = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);
76 return z0 * sd + mean;
79 static std::unique_ptr<Random> default_random(new XbtRandom);
83 default_random.reset(new XbtRandom);
87 default_random.reset(new StdRandom);
90 void set_mersenne_seed(int seed)
92 default_random->set_seed(seed);
95 int uniform_int(int min, int max)
97 return default_random->uniform_int(min, max);
100 double uniform_real(double min, double max)
102 return default_random->uniform_real(min, max);
105 double exponential(double lambda)
107 return default_random->exponential(lambda);
110 double normal(double mean, double sd)
112 return default_random->normal(mean, sd);
115 } // namespace random
117 } // namespace simgrid