Mail Archives: djgpp/1996/08/30/03:26:15
kagel AT quasar DOT bloomberg DOT com wrote:
>
> just call random(), after using srandom() to seed the generator, modulo the
> result and add one. The following will give a number between 1 and 50
> inclusive:
>
> long num;
>
> #define MAX_RAND 50
>
> srandom( time(NULL) );
>
> num = random();
> num = (num % MAX_RAND) + 1;
>
IMHO, this is **not** a good idea :
many random number generators use linear congruences :
they calculate one random number after the other by iterating formulae
like :
next=a next + b (a and b being ints),
in this formula :
if a is even, next is always the same as b (even if b is, odd if b is).
if b is odd, next follows the scheme even-odd-even-odd...
This is not a very random way of behaving... in particular, if n=2, your
formula will generate "clockwork random numbers..."
Worse still, many implementations of rand() use the "ANSI rand()"
formula, as above with
a=1103515245
b=12345
As you can see, these are both multiplies of 5, which means *any* random
number out of this generator will be a multiply of 5... and that its
parity will alternate even/odd... Even in simple applications, this can
have disastrous effects...
As DJGPP have a slightly different way of proceeding, this effect does
not appear here, *this does not make the above method better* : basically
this is a problem with all linear congrunet method, and DJGPP use one of
them...
There is an easy solution to this : divide, instead of using "%". It
should be just the same in terms of speed (calculated by a DIV
instruction when n is not a power of 2, and by AND or BITSHIFT when it
is) and will guarantee your random numbers to be random.
Regards,
Francois
- Raw text -