Andrew Koenig wrote in
Jon> for (int k = 0; k < 20; ++k)
Jon> {
Jon> int x = (rand() % maxrand) + 1;
Jon> cout << x << endl;
Jon> }
Jon> return 0;
Jon> }
Jon> Note that this may not give you very good random numbers,
Jon> depending on the implementation that comes with your compiler.
I can make a stronger statement than that -- in general, this
technique *will* not give you very good random numbers, regardless how
good the implementation is that comes with your compiler. Moreover,
the larger maxrand is, the worse the random numbers will be.
Here's why. The built-in rand function is not required to yield
random numbers larger than 32767. Suppose, for the sake of argument,
that this particular implementation does limit its random numbers to
0<=n<=32767, and that instead of maxrand being 10, it is 10,000.
Then:
if rand() yields then x will be
0 <= rand() < 10000 0
10000 <= rand() <= 20000 1
20000 <= rand() <= 30000 2
30000 <= rand() <= 32767 0
You will see that 0 will show up substantially more often than 1 or 2.
I think you mixed up you're tables for operator / with those for
operator %.
equation is x = (rand() % maxrand) + 1;
maxrand is 10000.
if rand() yields then x will be
0 <= rand() < 10000 rand() + 1
10000 <= rand() <= 20000 rand() - 10000 + 1
20000 <= rand() <= 30000 rand() - 20000 + 1
30000 <= rand() <= 32767 rand() - 30000 + 1
the 4th set gives a range of [1, 2768] all the others give a range
of [1, 10000].
This lead's to values in the range [1, 2768] being more likely
than values in the range [2769, 10000].
probability in [1, 2768] = 4 / 32768.0 and
probability in [2769, 10000] = 3 / 32768.0
If maxrange = 10 then we have (RAND_MAX) % 10 == 7 and
(RAND_MAX / 10 == 3276 so we get:
probability in [1, 8] = (3276 + 1) / 32768.0 and
probability in [9, 10] = 3276 / 32768.0
Rob.