Googles appar
Huvudmeny

Post a Comment On: cbloom rants

"02-19-09 - Two Code Gems"

5 Comments -

1 – 5 of 5
Blogger won3d said...

rand_mod?

February 19, 2009 at 10:34 AM

Blogger ryg said...

There's some additional gotchas if you really need (or want) your distribution to be as close to actually uniform as possible (online gambling would be an example). The first thing is that you're likely to use a PRNG that outputs a fixed number of random bits (typically 16 or 32). If your "count" is not a power of 2, it's important to note that any function from {0,...,2^n-1} to {0, 1, ..., count-1} will hit some numbers more often that others (this is just the pigeonhole principle). So if you really need the distribution to be perfectly flat, your best bet is to first generate n-bit random numbers where n=ceil(log2(count)) "the usual way", and just reject the ones that are >=count.

The other point is that the number of permutations is huge, even for relatively small n. For example, if you're shuffling a deck of 52 cards, your PRNG needs to have a state of at least log2(52!)=225.581... bits to even be theoretically able to produce every possible permutation (you actually want some more bits, again to avoid noticeable bias). A generator with 32-bit state will only ever generate a comperatively tiny subset of all possible permutations.

February 19, 2009 at 12:03 PM

Blogger ryg said...

And now I notice this is all on Wikipedia, too: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle - damn, could've saved some typing :)

February 19, 2009 at 12:04 PM

Blogger cbloom said...

Ah, wow, that's a good article.

In general I have found that trial-reject-retry is a very easy method to generate correctly distributed randoms with arbitrary probabilities. Hmm I wrote about that before.

February 19, 2009 at 1:28 PM

Blogger cacapee said...

A thing that I noticed while reading was that you are swapping from the 0th element onwards. Whereas the actual shuffle does it from the last element downwards. A small point but I thought I'd point it out regardless.

February 19, 2009 at 2:13 PM

You can use some HTML tags, such as <b>, <i>, <a>

This blog does not allow anonymous comments.

Comment moderation has been enabled. All comments must be approved by the blog author.

You will be asked to sign in after submitting your comment.