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