GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/util/random.cpp Lines: 24 24 100.0 %
Date: 2021-09-07 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
16236
Random::Random(uint64_t seed) { setSeed(seed); }
26
27
26163
void Random::setSeed(uint64_t seed)
28
{
29
26163
  d_seed = seed == 0 ? ~seed : seed;
30
26163
  d_state = d_seed;
31
26163
}
32
33
3489
uint64_t Random::operator()() { return rand(); }
34
35
4253538
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
4253538
  d_state ^= d_state >> 12;
41
4253538
  d_state ^= d_state << 25;
42
4253538
  d_state ^= d_state >> 27;
43
4253538
  return d_state * uint64_t{2685821657736338717};
44
}
45
46
4249688
uint64_t Random::pick(uint64_t from, uint64_t to)
47
{
48
4249688
  Assert(from <= to);
49
4249688
  Assert(to < UINT64_MAX);
50
4249688
  return (Random::rand() % (to - from + 1)) + from;
51
}
52
53
361
double Random::pickDouble(double from, double to)
54
{
55
361
  Assert(from <= to);
56
361
  Assert(to <= DBL_MAX);
57
361
  return Random::rand() * (to - from) + from;
58
}
59
60
3309104
bool Random::pickWithProb(double probability)
61
{
62
3309104
  Assert(probability <= 1);
63
3309104
  uint64_t p = (uint64_t) (probability * 1000);
64
3309104
  uint64_t r = pick(0, 999);
65
3309104
  return r < p;
66
}
67
68
}  // namespace cvc5