Get true or false with a given probability

前端 未结 2 992
你的背包
你的背包 2021-02-14 15:12

I\'m trying to write a function in c++ that will return true or false based on a probability given. So, for example if the probability given was 0.634 then, 63.4% of the time th

2条回答
  •  情深已故
    2021-02-14 16:10

    #include 
    bool prob_true(double p){
        return rand()/(RAND_MAX+1.0) < p;
    }
    

    Logic:

    rand() returns a random number between 0 and RAND_MAX (including both), with equal probability for each number. So by dividing the result by RAND_MAX we get a random number between 0 and 1. This allows us to choose a area of - in your example 63.4% of this segment, e.g. from 0 to 0.634 - and check if the result fell in that area.

    Now comes the tricky part: we don't want to get both 0 and 1! Why? Because we want probability 0 to never be true, that's why we need the (rather than the <=p) - so that when p=0 you'll never get true.

    However, if you can also have 1 as the result, then in the case where p=1 there is a very small chance you get false!

    That's why instead of dividing by MAX_RAND you divide by MAX_RAND+1.0. Also note that I added 1.0 instead of 1 to turn the number into a double (otherwise I might get an overflow if MAX_RAND==INT_MAX)

    Finally, here's an alternate implementation without the division:

    #include 
    bool prob_true(double p){
        return rand() < p * (RAND_MAX+1.0);
    }
    

提交回复
热议问题