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

Line Exec Source
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-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.\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/check.h"
23
24
namespace CVC4 {
25
26
12061
Random::Random(uint64_t seed) { setSeed(seed); }
27
28
21058
void Random::setSeed(uint64_t seed)
29
{
30
21058
  d_seed = seed == 0 ? ~seed : seed;
31
21058
  d_state = d_seed;
32
21058
}
33
34
4751
uint64_t Random::operator()() { return rand(); }
35
36
5460281
uint64_t Random::rand()
37
{
38
  /* xorshift* generator (see S. Vigna, An experimental exploration of
39
   * Marsaglia's xorshift generators, scrambled. ACM Trans. Math. Softw.
40
   * 42(4): 30:1-30:23, 2016). */
41
5460281
  d_state ^= d_state >> 12;
42
5460281
  d_state ^= d_state << 25;
43
5460281
  d_state ^= d_state >> 27;
44
5460281
  return d_state * uint64_t{2685821657736338717};
45
}
46
47
5454936
uint64_t Random::pick(uint64_t from, uint64_t to)
48
{
49
5454936
  Assert(from <= to);
50
5454936
  Assert(to < UINT64_MAX);
51
5454936
  return (Random::rand() % (to - from + 1)) + from;
52
}
53
54
594
double Random::pickDouble(double from, double to)
55
{
56
594
  Assert(from <= to);
57
594
  Assert(to <= DBL_MAX);
58
594
  return Random::rand() * (to - from) + from;
59
}
60
61
4065904
bool Random::pickWithProb(double probability)
62
{
63
4065904
  Assert(probability <= 1);
64
4065904
  uint64_t p = (uint64_t) (probability * 1000);
65
4065904
  uint64_t r = pick(0, 999);
66
4065904
  return r < p;
67
}
68
69
}