How can I generate a random boolean with a probability of p (where 0 <= p <= 1.0) using the C standard library rand() function?
p
rand()
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); }
2.1m questions
2.1m answers
60 comments
57.0k users