i’m getting a bit confused with operators and there use with random generation. I guess i’m just asking does this code do what I want it to?
Generate a ‘random’ TRUE or FALSE depending on what probability I assigned the function.
bool randtf(int probability) {
if ((rand() % 100) < probability)
return true;
else
return false;
}
so if randtf(63) it has a 63% chance of being TRUE?
Any guidance would be much appreciated. Thanks.
Yes, to a first approximation.
No, more accurately.
rand()returns a number between0andRAND_MAX, which in practice will always be of the form(1 << n) - 1. This isn’t a multiple of 100, so you won’t get a perfectly uniform distribution when you take the modulo.You can fix that by using rejection sampling. For the sake of argument, let’s assume
RAND_MAX == 32767(i.e. 16-bit). The first step is to keep generating random numbers, rejecting them until you obtain one less than 32700 (the largest multiple of 100 that’s less thanRAND_MAX). If you then do the modulo trick on that, you will get a uniform distribution.Of course, this assumes a sane, statistically robust, implementation of
rand(), which is quite an assumption!