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 ...
}
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 ...
}
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
.
bool nextBool(double probability)
{
return (rand() / (double)RAND_MAX) < probability;
}
or (after seeing other responses)
bool nextBool(double probability)
{
return rand() < probability * RAND_MAX;
}