Message-Id: <2.2.32.19970530194714.006c3788@gate> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Date: Fri, 30 May 1997 12:47:14 -0700 To: "Matthew Bennett" From: "Alan Wilson" Subject: Re: Random numbers Cc: djgpp AT delorie DOT com Precedence: bulk At 11:09 AM 5/30/97 GMT, you wrote: >Hi all, > >When using the 'random' command in the form: > >printf("%d\n", random() & 10); > >The numbers produced are always either 0, 2, 8 or 10. If I use say 2 as my >range, the numbers produced are only 0 or 2. I don't seem to be able to >get a well varied set of random numbers (i.e. all the numbers in the range >eventually appear). Using the command form: > >prinf("%d\n", random(10)); > >produces the same sequence of very large numbers - whatever range I use. > >Does anyone know how I can get a sequence of in-range, varied numbers? >For what I'm writing, it would also need to be seeded (the 'srandom' >command is what I'm currently using). > >Thanks, The following is some comments that some people sent me after I asked a similar qustion about random numbers...Hope it helps. ------------------------ "if you were more interested in algorithms to generate random numbers I'd suggest you get (or rather, borrow) Knuth's Seminumerical Algorithms - The Art of Computer Programming, Volume 2. Half the book is about random numbers, how to generate them, how random they are, etc. Only get this if you are heavily into mathematics, though! You could, of course, also look at the source code for the rand[om]() functions in libc. -- George Foot " ------------------- "On getting random numbers : If you do a histogram of rand() % 100 or random() % 100 you will find that its not uniform. If you image that rand return a uniform number from 0-31 and you % 10 you map [ rand val ] -> (val % 10) [0,10,20,30] -> 0 [1,11,21,31] -> 1 [2,12,22] -> 2 [3,13,23] -> 3 [4,14,24] -> 4 . . . . [9,19,29] -> 9 Depending on what your doing it may be close enough not to matter. Somthing like this gets rid of this problem. int rnd(int lo,int hi) { int rng = hi - lo + 1; return ( lo + rng * rand() / MAX_INT ); } I only spent a couple days trying to find why a modeler I was writing always favored low number 8^)....eheft AT dnaco DOT net (Eric Heft)" ---------------------------- "The easyest way is to use the random function from the stdlib library. like so x = random() % 100; You can make more realistic random numbers by using the current time as a seed. I can't remember the seed command but I think it's randomize(x). Hope this is helpfull, you should also consult the documentation that comes with DJGPP. Cheers, Timothy Gunn " Alan Wilson