lundi 2 novembre 2015

Unbiase coin toss using the C++11 random library

I have a program that needs to generate very many 0/1 random values. Because this is needed many times and in different part of the code, I wish to have an efficient and easy to use random generator to perform this task.

I started using the standard library <random> from C++11 to do so but the documentation is quite sparse and sometimes even contradictory.

My questions were the following:

  • Should I extract bits myself (using masking on unsigned long long) or can the library do it on its own?

    Indeed, I found a document that says:

Better still, standard-conforming distributions cope with all engine corner cases, even unlikely ones. For example, if an engine delivers fewer bits per call than needed, the distribution will make multiple calls until it has enough bits to let it satisfy the entire desired range of variates. On the other hand, if an engine produces more bits than needed, a distribution is free to cache the excess for use the next time it is called.

  • Does this mean that it will automatically use only two bits to generate 0 and 1?
    • If yes, should I use the uniform_int_distribution or the bernoulli_distributio (bool) distribution with probability 0.5? (What would be most efficient?)
    • If no, what is the most efficient way to generate a lot of random bits with the random library?



Aucun commentaire:

Enregistrer un commentaire