0

I‘m reading the C++ reference for rand() which returns a randomly distributed number in a specific range. For getting random numbers in the range 0-99, one can simply use a modulo operation:

int random0to99 = rand() % 100;

In the reference, it is additionally stated that:

Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).

Why? Why isn‘t rand() % 100 uniformly distributed when rand() is?

ATW
  • 233
  • 2
  • 14
  • Who told you `std::rand` produces uniformly distributed random numbers? – Brian61354270 Dec 05 '20 at 19:21
  • 2
    Prefer [cppreference](https://en.cppreference.com/w/cpp/numeric/random/rand) for C++ documentation. – Kostas Dec 05 '20 at 19:21
  • 3
    Related: [https://stackoverflow.com/questions/13104478/uniformity-of-random-numbers-taken-modulo-n](https://stackoverflow.com/questions/13104478/uniformity-of-random-numbers-taken-modulo-n) – drescherjm Dec 05 '20 at 19:23
  • 2
    Also: [https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator](https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator) – drescherjm Dec 05 '20 at 19:23
  • @Brian doesn‘t „pseudo-random“ mean uniformly distributed? – ATW Dec 05 '20 at 19:23
  • Thanks @drescherjm. That answered my question. – ATW Dec 05 '20 at 19:24
  • 4
    consider how `rand() % 100` would be distributed if `RAND_MAX` was `150` – 463035818_is_not_an_ai Dec 05 '20 at 19:28
  • 1
    @ATW, Theoretically, `rand` can be of high quality, but implementations have traditionally been pretty poor. I suspect there's a fear of changing them because of Hyrum's Law, although the concern there could be well-founded. (As a thought experiment, imagine if Minecraft seeds were suddenly completely different; it would piss off a pretty large community.) – chris Dec 05 '20 at 19:29

0 Answers0