views:

77

answers:

2

How can I generate a random boolean with a probability of p (where 0 <= p <= 1.0) using the C standard library rand() function?

i.e.

bool nextBool(double probability)
{
    return ...
}
A: 

Do you mean generate a random variable so that p(1) = p and p(0) = (1-p)?

If so, compare the output of rand() to p*RAND_MAX.

Oli Charlesworth
+2  A: 
bool nextBool(double probability)
{
    return (rand() / (double)RAND_MAX) < probability;
}

or (after seeing other responses)

bool nextBool(double probability)
{
    return rand() <  probability * RAND_MAX;
}
Colin
+1 Perfect, thanks (top one).
Jake Petroules
The second one might actually be faster. They're mathematically identical.
Colin
That needs to be `probability * (RAND_MAX + 1)` - otherwise, passing a value of `1.0` as `probability` will result in the function returning 0 sometimes.
caf
@caf Good catch, thanks for pointing that out.
Jake Petroules