[vox-tech] help: random number problem in C (yet again!)
Rod Roark
vox-tech@lists.lugod.org
Sat, 20 Apr 2002 11:15:32 -0700
On my bleeding-edge Gentoo machine, "man 3 rand" says "The rand()=20
function returns a pseudo-random integer between 0 and RAND_MAX."
Perhaps this is _inclusive_ of RAND_MAX, since an example in the same man=
=20
page includes the term 10.0*rand()/(RAND_MAX+1.0). This is also consiste=
nt=20
with the notion that "MAX" stands for "maximum".
-- Rod
http://www.sunsetsystems.com/
On Saturday 20 April 2002 10:49 am, Peter Jay Salzman wrote:
> hello all,
>
> given the code:
>
> #include <stdio.h>
> #include <stdlib.h>
> int Irand(int low, int high);
>
>
> int main(void)
> {
> unsigned int N =3D 4;
> unsigned int M =3D 4;
> unsigned int count =3D 0;
> int x, y;
> srand(2844604396);
>
> while (1) {
> ++count;
> x =3D Irand(0, N-1);
> if (x<0 || x>3) {
> printf("count: %u, x: %u\n", count, x);
> exit(0);
> }
> }
>
> }
>
>
> int Irand(int low, int high)
> {
> return low + (int)( (double)(high-low+1) * rand()/RAND_MAX );
> }
>
>
> when count =3D 109595656, the random number generator (which should onl=
y
> return integers between 0 and 3) returns a 4.
>
> clearly, my random number generator is faulty, but i can't figure out
> why i should return a 4. and after 109595656 calls, this is a very
> uncommon occurance!
>
> does anyone know why this subroutine should return a 4 under any
> circumstances?
>
> can someone suggest a better subroutine to calculate an integer between
> low and high?
>
> btw, the seed is set to a particular value because i was tracking down =
a
> problem. normally, my seed is obtained through a call to:
>
> unsigned int SeedRandomGenerator(void)
> {
> unsigned int seed;
> FILE *fp;
>
> if( (fp =3D fopen("/dev/random", "r")) =3D=3D NULL)
> die("Can't open /dev/random for reading.");
> fread(&seed, sizeof(unsigned int), 1, fp);
> fclose(fp);
> srand(seed);
> return seed;
> }
>
> this is a show stopper for me. any help greatly appreciated!!
>
> pete
> _______________________________________________
> vox-tech mailing list
> vox-tech@lists.lugod.org
> http://lists.lugod.org/mailman/listinfo/vox-tech