Add random number generator. (#1370)
[cvc5.git] / src / util / random.cpp
1 /********************* */
2 /*! \file random.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Aina Niemetz
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2017 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief A Random Number Generator.
13 **
14 ** A random number generator, implements the xorshift* generator
15 ** (see S. Vigna, An experimental exploration of Marsaglia's xorshift
16 ** generators, scrambled. ACM Trans. Math. Softw. 42(4): 30:1-30:23, 2016).
17 **/
18
19 #include "util/random.h"
20
21 #include <cfloat>
22 #include "base/cvc4_assert.h"
23
24 namespace CVC4 {
25
26 uint64_t Random::rand()
27 {
28 /* xorshift* generator (see S. Vigna, An experimental exploration of
29 * Marsaglia's xorshift generators, scrambled. ACM Trans. Math. Softw.
30 * 42(4): 30:1-30:23, 2016). */
31 d_state ^= d_state >> 12;
32 d_state ^= d_state << 25;
33 d_state ^= d_state >> 27;
34 d_state *= uint64_t{2685821657736338717};
35 return d_state;
36 }
37
38 uint64_t Random::pick(uint64_t from, uint64_t to)
39 {
40 Assert(from <= to);
41 Assert(to < UINT64_MAX);
42 return (Random::rand() % (to - from + 1)) + from;
43 }
44
45 double Random::pickDouble(double from, double to)
46 {
47 Assert(from <= to);
48 Assert(to <= DBL_MAX);
49 return Random::rand() * (to - from) + from;
50 }
51
52 bool Random::pickWithProb(double probability)
53 {
54 Assert(probability <= 1);
55 uint64_t p = (uint64_t) (probability * 1000);
56 uint64_t r = pick(0, 999);
57 return r < p;
58 }
59
60 }