Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Efficient way to generate random bitset with configurable mean "1s to 0s" ratio

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 1s 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 1s. It's going to be used in a very computation-heavy application, so every possible optimization is welcome.

like image 671
Kuba Orlik Avatar asked Aug 07 '14 07:08

Kuba Orlik


1 Answers

Bernoulli distribution is a probability distribution of 1 or 0 in a single experiment. A sum of many such distributed variables

enter image description here

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

like image 152
4pie0 Avatar answered Sep 22 '22 13:09

4pie0