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
#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 (rather than the However, if you can also have That's why instead of dividing by Finally, here's an alternate implementation without the division:0
and 1
! Why? Because we want probability 0
to never be true, that's why we need the <=p
) - so that when p=0
you'll never get true.1
as the result, then in the case where p=1
there is a very small chance you get false!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
)#include