Originally Posted by
laserlight
RAND_MAX is guaranteed to be at least 32767, but on some somewhat commonly used implementations it is much greater than that.
True, I have seen that and was very pleasantly surprised. But on gcc4.6.1 and MSVC2010 it still seems to be the puny 32767.
Originally Posted by
laserlight
you'll need to check the value of RAND_MAX first or risk undefined behaviour from the left shift on a signed integer.
Right, so I should have posted something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#if RAND_MAX != 32767
#error RAND_MAX must be 32767 for this code to work
#endif
/* Returns 30 bits: range [0, 1073741823] */
int rnd30(void) {
return (rand() << 15 | rand());
}
int main(void) {
int i;
srand(time(0));
for (i = 0; i < 100; i++)
printf("%d\n", rnd30() % 100000);
return 0;
}
Of course this doesn't deal with the extra probability of the lower numbers, but the OP doesn't seem to concerned (and in the above case, with a modulus of 100000, the lower 41824 numbers, incl. 0, have only a 0.09% greater change of appearing).
Actually, I did have a more complicated scheme that throws away the lower 2 bits of rand()'s return value (because they are supposedly less random then the other bits) and also includes a loop to get rid of that extra probability of lower numbers:
Code:
/* Random 26 bits: range [0,67108863] */
int rnd(int n) {
int limit = 67108863 / n * n;
int r;
do
r = rand() >> 2 | (rand() & 0xfffc) << 11;
while (r > limit);
return r % n;
}
// Since it includes the modulus, call it like:
r = rnd(100000);