Random Numbers ...

Frank Adams franka at mmintl.UUCP
Sat Feb 27 14:06:28 AEST 1988


In article <5555 at cit-vax.Caltech.Edu> wen-king at cit-vlsi.UUCP (Wen-King Su) writes:
>In general, the correct way to do it is to use a random number generator
>of an appropriate range (the smallest power of 2 that is large enough to
>cover all the numbers you need).  Then[:]
>
>unsigned my_random_source();
>
>my_random(range)
>    int range;
>{
>    int value;
>    do { value = my_random_source(); } while(value >= range);
>    return(value);
>}

This is fine if 'range' is a reasonably large number.  On the other hand, if
it is 2, it works very badly.  More generally, try:

unsigned my_random_source();
int source_limit;

my_random(range)
    int range;
{
    int value;
    int multiplicity = source_limit / range;
    int limit = multiplicity * range

    do { value = my_random_source(); } while(value >= limit);

    return(value / multiplicity);
}

To be on the safe side, you could add a check for limit != 0.  There are
techniques for dealing with that case, but it is usually best to just
increase the size of the numbers you are getting from the generator.
-- 

Frank Adams                           ihnp4!philabs!pwa-b!mmintl!franka
Ashton-Tate          52 Oakland Ave North         E. Hartford, CT 06108



More information about the Comp.lang.c mailing list