How to generate a boolean with p probability using

2019-01-27 18:44发布

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 ...
}

标签: c random
3条回答
唯我独甜
2楼-- · 2019-01-27 18:56

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.

查看更多
爷、活的狠高调
3楼-- · 2019-01-27 19:12

The following generator should not be biased, given rand() efficiently uniform and independent:

bool nextBool(double probability)
{
    double p_scaled = probability * (RAND_MAX+1) - rand();
    if ( p_scaled >= 1 ) return true;
    if ( p_scaled <= 0 ) return false;
    return random_bool( p_scaled );
}

Note, that while function is recursive,

  1. probability of the recursive call is 1.0/RAND_MAX, i.e quite small,
  2. it has to be recursive or in some other way call rand() multiple times, if you want to use probability different from multiples of 1.0/RAND_MAX.

Also note, that the probability is still a little bit biased. See this question.

查看更多
时光不老,我们不散
4楼-- · 2019-01-27 19:17
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);
}
查看更多
登录 后发表回答