1 |
|
/****************************************************************************** |
2 |
|
* Top contributors (to current version): |
3 |
|
* Aina Niemetz |
4 |
|
* |
5 |
|
* This file is part of the cvc5 project. |
6 |
|
* |
7 |
|
* Copyright (c) 2009-2021 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. |
11 |
|
* **************************************************************************** |
12 |
|
* |
13 |
|
* A random number generator, implements the xorshift* generator |
14 |
|
* (see S. Vigna, An experimental exploration of Marsaglia's xorshift |
15 |
|
* generators, scrambled. ACM Trans. Math. Softw. 42(4): 30:1-30:23, 2016). |
16 |
|
*/ |
17 |
|
|
18 |
|
#include "util/random.h" |
19 |
|
|
20 |
|
#include <cfloat> |
21 |
|
#include "base/check.h" |
22 |
|
|
23 |
|
namespace cvc5 { |
24 |
|
|
25 |
16240 |
Random::Random(uint64_t seed) { setSeed(seed); } |
26 |
|
|
27 |
26156 |
void Random::setSeed(uint64_t seed) |
28 |
|
{ |
29 |
26156 |
d_seed = seed == 0 ? ~seed : seed; |
30 |
26156 |
d_state = d_seed; |
31 |
26156 |
} |
32 |
|
|
33 |
3489 |
uint64_t Random::operator()() { return rand(); } |
34 |
|
|
35 |
4245802 |
uint64_t Random::rand() |
36 |
|
{ |
37 |
|
/* xorshift* generator (see S. Vigna, An experimental exploration of |
38 |
|
* Marsaglia's xorshift generators, scrambled. ACM Trans. Math. Softw. |
39 |
|
* 42(4): 30:1-30:23, 2016). */ |
40 |
4245802 |
d_state ^= d_state >> 12; |
41 |
4245802 |
d_state ^= d_state << 25; |
42 |
4245802 |
d_state ^= d_state >> 27; |
43 |
4245802 |
return d_state * uint64_t{2685821657736338717}; |
44 |
|
} |
45 |
|
|
46 |
4241955 |
uint64_t Random::pick(uint64_t from, uint64_t to) |
47 |
|
{ |
48 |
4241955 |
Assert(from <= to); |
49 |
4241955 |
Assert(to < UINT64_MAX); |
50 |
4241955 |
return (Random::rand() % (to - from + 1)) + from; |
51 |
|
} |
52 |
|
|
53 |
358 |
double Random::pickDouble(double from, double to) |
54 |
|
{ |
55 |
358 |
Assert(from <= to); |
56 |
358 |
Assert(to <= DBL_MAX); |
57 |
358 |
return Random::rand() * (to - from) + from; |
58 |
|
} |
59 |
|
|
60 |
3301371 |
bool Random::pickWithProb(double probability) |
61 |
|
{ |
62 |
3301371 |
Assert(probability <= 1); |
63 |
3301371 |
uint64_t p = (uint64_t) (probability * 1000); |
64 |
3301371 |
uint64_t r = pick(0, 999); |
65 |
3301371 |
return r < p; |
66 |
|
} |
67 |
|
|
68 |
|
} // namespace cvc5 |