Message-ID: <3321274F.6266@pobox.oleane.com> Date: Sat, 08 Mar 1997 09:46:07 +0100 From: Francois Charton Organization: CCMSA MIME-Version: 1.0 To: djgpp AT delorie DOT com Subject: Re: a randomize function for DJGPP? References: <5flbpp$m74 AT nr1 DOT ottawa DOT istar DOT net> <331FC0D1 DOT 1A26 AT cs DOT com> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit John M. Aldrich wrote: > >To get a random number from 0 to X - 1, use: > > n = random( ) % X; > >Before everybody gets hysterical on me again, let me say in advance that >the GNU random() RNG, unlike rand(), is guaranteed to be random in the >lower bits, so you can use the mod operator safely. Yes, but then you are taking chances about portability: rand() is an ANSI library function, and could be implemented in a less intelligent way on other systems or with other compilers... Actually, chances are high that is will be so: the ANSI comitee itself has published such an algorithm as a example, so many programmers will certainly copy it. IMHO, it is better to use the divide than the mod operation: precalculate RAND_MAX/X, and do rand()/(RAND_MAX/X), it is as fast as the mod, a little less readable (if you are afraid about that, use a macro to make it clearer to readers of your code), and it is guaranteed to be portable. (It is a bit like the void main(void) vs int main(void) problem) the former is usable in many cases, but still not a good idea). While we are at it, did anyone try some good random generator crash test suite (like the tests in Knuth for instance) on rand() and random()? Francois