Mail Archives: djgpp/1997/11/04/21:20:15
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 <stdlib.h>). random()
goes from 0 to MAXINT (#defined in <values.h>). 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
- Raw text -