I'm looking for a highly efficient way to generate random std::bitset
of set length. I'd also like to be able to influence the probability of 1
s appearing in the result, so if the probability value is set low enough, only a small percentage of all the results will even contain a 1
, but it's still possible (but very unlikely) to result in all 1
s. It's going to be used in a very computation-heavy application, so every possible optimization is welcome.
Bernoulli distribution is a probability distribution of 1 or 0 in a single experiment. A sum of many such distributed variables
gives a variable distributed with mean n*p (binomial distribution). So by taking n bernoulli distributed bits with probability of 1 given by p we get a bitset of size n and np bits set to 1 on average. Of course this is just a starting point to optimize next if the efficiency this offers is not enough.
#include <iostream>
#include <random>
#include <bitset>
template< size_t size>
typename std::bitset<size> random_bitset( double p = 0.5) {
typename std::bitset<size> bits;
std::random_device rd;
std::mt19937 gen( rd());
std::bernoulli_distribution d( p);
for( int n = 0; n < size; ++n) {
bits[ n] = d( gen);
}
return bits;
}
int main()
{
for( int n = 0; n < 10; ++n) {
std::cout << random_bitset<10>( 0.25) << std::endl;
}
}
result:
1010101001
0001000000
1000000000
0110010000
1000000000
0000110100
0001000000
0000000000
1000010000
0101010000
http://ideone.com/p29Pbz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With