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()
top*RAND_MAX
.The following generator should not be biased, given rand() efficiently uniform and independent:
Note, that while function is recursive,
1.0/RAND_MAX
, i.e quite small,rand()
multiple times, if you want to useprobability
different from multiples of1.0/RAND_MAX
.Also note, that the probability is still a little bit biased. See this question.
or (after seeing other responses)