Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a boolean with p probability using C rand() function?

Tags:

c

random

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 ...
}
like image 493
Jake Petroules Avatar asked Feb 03 '23 02:02

Jake Petroules


2 Answers

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);
}
like image 135
Colin Avatar answered Feb 05 '23 16:02

Colin


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.

like image 26
Oliver Charlesworth Avatar answered Feb 05 '23 16:02

Oliver Charlesworth