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

前端 未结 3 734
深忆病人
深忆病人 2020-12-20 15:48

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 15:57

    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.

提交回复
热议问题