Date: Tue, 4 Nov 1997 18:19:01 -0800 (PST) Message-Id: <199711050219.SAA15044@adit.ap.net> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" To: eblazecka AT bc DOT sympatico DOT ca, djgpp AT delorie DOT com From: Nate Eldredge Subject: Re: rand() or random() Precedence: bulk At 11:20 11/3/1997 -0800, Ryan Blazecka wrote: >Mark Phillips wrote: >> Just for the heck of it, say I want to get a random number from 0 to >> 19. rand() and random() appear to return numbers from 0 to 2^31. I >> could always do rand() * 20 / 2^31 but there must be a better way. rand() returns values from 0 to RAND_MAX (#defined in ). random() goes from 0 to MAXINT (#defined in ). On DJGPP they happen to both be the same, and equal to 2^31. > >How about rand() % 19? :) That does work, but perhaps not so well with some other random number generator where the low-order bits aren't so random. My personal favorite method is this: (int)((double)rand() / (double)RAND_MAX)) * 20 I realize this does involve floating point, but you don't have to worry about integer overflow or low-order non-randomness. Also, I find it clearer mathematically. > >(BTW, you should use random() instead of rand(), its numbers are more >"random") Agreed. Compare the sources and be amazed. :) I just wonder why ANSI programs get punished by having to use the worse generator, while incompatible BSD-isms are rewarded. Nate Eldredge eldredge AT ap DOT net