x + (rand() % y - x + 1)
this is a formula to find a random number between x and y but I don't know how it was made I want a logical/mathematical explanation for it and thank you in advance.

- 28,148
- 6
- 56
- 87

- 1
- 1
-
9It's incorrect, it should be `x + (rand() % (y - x + 1))`. – HolyBlackCat Apr 01 '20 at 14:19
-
1Because you've left out parentheses, the formula will produce a value between `1` and `y`. The `x` terms cancel out. – Peter Apr 01 '20 at 14:25
-
Even with corrections, you should avoid this algorithm due to [modulo bias](https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). – pjs Apr 01 '20 at 15:49
1 Answers
First, your code should be corrected to x + (rand() % (y - x + 1))
The rand
function generates a pseudo random positive integer between 0
and RAND_MAX
which is typically implemented by PMMLCG algorithm by Hutchinson. When we assume RAND_MAX
is large enough, then the occurrence possibilities of any positive integer are the same. And so, when you apply the result to a mod
operation, let's say, %n
, then we will have a pseudo random integer in the interval [0, n-1]
In your example, (rand() % (y - x + 1))
generates a pseudo random integer between [0, y-x]
and when we add x
on it, we get a pseudo random between [x, y]
However, as a supplement, this algorithm has what I would describe as severe problems, the most obvious of which is it relies on the value of RAND_MAX
. The standard only guarantee that it's a integer not less than 32767
, which is a very small value and so it can contribute to the unevenness of the occurrence possibility of the candidates in the interval.
I suggest you learn to use <random>
library in C++11:https://en.cppreference.com/w/cpp/header/random

- 1,368
- 5
- 18
-
@FrançoisAndrieux I had thought to add "typically", but somehow I forgot... Thanks for pointing out. – con ko Apr 01 '20 at 15:20