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