I need to generate random Boolean values on a performance-critical path.
The code which I wrote for this is
std::random_device rd;
std::uniform_int_distribution<> randomizer(0, 1);
const int val randomizer(std::mt19937(rd()));
const bool isDirectionChanged = static_cast<bool>(val);
But do not think that this is the best way to do this as I do not like doing static_cast<bool>
.
On the web I have found a few more solutions
1. std::bernoulli_distribution
2. bool randbool = rand() & 1;
Remember to call srand()
at the beginning.
I would prefill a (long enough) (circular) buffer of 64bit random values, and then take very quickly one bit at a time when in need of a boolean random value
Of course the class can be made general to the buffer size, the random generator, the base type (doesn't necessarily have to be uint64_t) etc.
Accessing the buffer only once every 64 calls:
A way would be to just generate a
unsigned long long
for every 64 random calls as stated in the comments. An example:Unless you have further constraints on the randomness you need, the fastest way to generate a random bool is:
To be more specific, there are thousands of ways to generate random boolean numbers, all satisfying different constraints, and many of them do not deliver "truly" random numbers (that includes all the other answers so far). The word "random" alone does not tell anyone what properties you really need.