What are the advantages of using uniform_int_distribution vs a modulus operation?

You will get statistical bias when you use modulo (%) to map the range of e.g. rand() to another interval.

E.g suppose rand() maps uniformly (without bias) to [0, 32767] and you want to map to [0,4] doing rand() % 5. Then the values 0, 1, and 2 will on average be produced 6554 out of 32768 times, but the values 3 and 4 only 6553 times (so that 3 * 6554 + 2 * 6553 = 32768).

The bias is small (0.01%) but depending on your application that could prove fatal. Watch Stephan T. Lavavej’s talk “rand() considered harmful” for more details.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)