Shuffle

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Jan 28 14:17:29 PST 2008


Sean Kelly wrote:
> Frits van Bommel wrote:
>> Both versions would be better if the randomizer eliminated modulo bias,
>> though :P.
> 
> I just fixed that as well I think.  Let me know if I screwed it up:
> 
> http://dsource.org/projects/tango/changeset/3139

Looks good, assuming libc's rand() has a uniform distribution over the 
lower 16 bits.

(This is probably just nitpicking:)
AFAICT that assumption isn't guaranteed by the C standard though, it 
seems RAND_MAX is only required to be >= 32767 (so rand() may well 
return 15-bit random numbers :( [1]).
Also, I can't find any mention of what the (lower-bitwise) distribution 
is supposed to be. For instance, if RAND_MAX happens to be (<some prime> 
- 1) instead of (2^N - 1) the lower bits won't be uniformly distributed 
even if the results of rand() are themselves distributed perfectly 
uniformly in [0 ... RAND_MAX].
For these reasons, it may not be a very good idea to use libc rand(). 
It's just underspecified AFAICT...

(I don't have the actual C standard though, just some library reference 
sites from my bookmarks and what Google drags up)



[1] For glibc RAND_MAX is 2^32-1 though, so this shouldn't be a problem 
on typical *nix systems. I'm not sure about Windows systems though; IIRC 
mingw (and presumably gdcwin) uses the MS libc and DMD uses its own libc...


More information about the Digitalmars-d-announce mailing list