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

前端 未结 3 626
深忆病人
深忆病人 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 16:07

    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);
    }
    

提交回复
热议问题