[comp.lang.c] Improved Random by Doug Gwyn ERROR, BUG, NO NO

wen-king@cit-vlsi.Caltech.Edu (Wen-King Su) (02/27/88)

In article <479@anuck.UUCP> jrl@anuck.UUCP (j.r.lupien) writes:
>
<long random(maxval)    /* Return psuedorandom val mod maxval */
>long maxval;
<{
>        maxval= (ranarray[idx1--]+=ranarray[idx2--])%maxval;
						^^^^^^^^^^^^
I want to point out that modulo on a set of uniformly distributed
random numbers does not yield another set of uniformaly distributed
unless the range of the random number source is an integer multiple
of maxval.  Neither is divide, this is a frequently made error.
There is another posting with a similar problem.  The author of that
posting has followed up with an new version that would work.

<        if(idx2<0) idx2=54;
>        if(idx1<0) idx1=54;
<        return ((maxval<0L)?(-maxval):maxval);
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is worse than the previous problem.  Assuming that maxval has
an uniform distribution, do you know this expression will return
0 half as frequently as any other numbers?  Use unsigned instead.

>}
<
>/* end of file random.c  */


/*------------------------------------------------------------------------*\
| Wen-King Su  wen-king@vlsi.caltech.edu  Caltech Corp of Cosmic Engineers |
\*------------------------------------------------------------------------*/