l i n u x - u s e r s - g r o u p - o f - d a v i s
L U G O D
 
Next Meeting:
December 2: Social gathering
Next Installfest:
TBD
Latest News:
Nov. 18: Club officer elections
Page last updated:
2002 Apr 20 11:14

The following is an archive of a post made to our 'vox-tech mailing list' by one of its subscribers.

Report this post as spam:

(Enter your email address)
[vox-tech] help: random number problem in C (yet again!)
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[vox-tech] help: random number problem in C (yet again!)



hello all,

given the code:

   #include <stdio.h>
   #include <stdlib.h>
   int Irand(int low, int high);
   
   
   int main(void)
   {
      unsigned int N = 4;
      unsigned int M = 4;
      unsigned int count = 0;
      int x, y;
      srand(2844604396);
   
      while (1) {
         ++count;
         x = 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 = 109595656, the random number generator (which should only
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 = fopen("/dev/random", "r")) == 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



LinkedIn
LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
facebook
LUGOD Group on Facebook
'Like' LUGOD on Facebook:

Hosting provided by:
Sunset Systems
Sunset Systems offers preconfigured Linux systems, remote system administration and custom software development.

LUGOD: Linux Users' Group of Davis
PO Box 2082, Davis, CA 95617
Contact Us

LUGOD is a 501(c)7 non-profit organization
based in Davis, California
and serving the Sacramento area.
"Linux" is a trademark of Linus Torvalds.

Sponsored in part by:
O'Reilly and Associates
For numerous book donations.