If performance is your only criterion, then the answer is :
bool get_random() { return true;
Unfortunately, the entropy of this random number is zero, but the performance is quite high.
Since I suspect that this random number generator is not very useful to you, you will need to quantify how random you want your Boolean to be . How about a 2048 cycle length? One million? 2 ^ 19937-1? To the end of the universe?
I suspect that since you have explicitly stated that performance is your biggest problem, then a good old-fashioned linear congruent generator may be "good enough." Based on this article , I assume that this generator period is about 32 * ((2 ^ 31) -5), or about 68 trillion. iterations. If this is not "good enough", you can add any C ++ 11 compatible generator that you like instead of minstd_rand.
For extra credit and a small performance hit, modify the code below to use the offset coin algorithm to remove the offset in the generator.
#include <iostream> #include <random> bool get_random() { typedef std::minstd_rand generator_type; typedef generator_type::result_type result_type; static generator_type generator; static unsigned int bits_remaining = 0; static result_type random_bits; if ( bits_remaining == 0 ) { random_bits = generator(); bits_remaining = sizeof( result_type ) * CHAR_BIT - 1; } return ( ( random_bits & ( 1 << bits_remaining-- ) ) != 0 ); } int main() { for ( unsigned int i = 0; i < 1000; i++ ) { std::cout << " Choice " << i << ": "; if ( get_random() ) std::cout << "true"; else std::cout << "false"; std::cout << std::endl; } }
johnwbyrd Feb 17 '16 at 2:21 2016-02-17 02:21
source share