GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/util/random.cpp Lines: 24 24 100.0 %
Date: 2021-08-01 Branches: 11 82 13.4 %

Line Exec Source
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
13501
Random::Random(uint64_t seed) { setSeed(seed); }
26
27
23340
void Random::setSeed(uint64_t seed)
28
{
29
23340
  d_seed = seed == 0 ? ~seed : seed;
30
23340
  d_state = d_seed;
31
23340
}
32
33
3238
uint64_t Random::operator()() { return rand(); }
34
35
4820988
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
4820988
  d_state ^= d_state >> 12;
41
4820988
  d_state ^= d_state << 25;
42
4820988
  d_state ^= d_state >> 27;
43
4820988
  return d_state * uint64_t{2685821657736338717};
44
}
45
46
4817398
uint64_t Random::pick(uint64_t from, uint64_t to)
47
{
48
4817398
  Assert(from <= to);
49
4817398
  Assert(to < UINT64_MAX);
50
4817398
  return (Random::rand() % (to - from + 1)) + from;
51
}
52
53
352
double Random::pickDouble(double from, double to)
54
{
55
352
  Assert(from <= to);
56
352
  Assert(to <= DBL_MAX);
57
352
  return Random::rand() * (to - from) + from;
58
}
59
60
3586219
bool Random::pickWithProb(double probability)
61
{
62
3586219
  Assert(probability <= 1);
63
3586219
  uint64_t p = (uint64_t) (probability * 1000);
64
3586219
  uint64_t r = pick(0, 999);
65
3586219
  return r < p;
66
}
67
68
}  // namespace cvc5