I was reading the tutorial located here:
http://faq.cprogramming.com/cgi-bin/...&id=1073086407
and there appear to be some errors. Here is the relevant part:
Removing the std:: specifiers, the random number code for the first method is:Quote:
This code shows two methods to use the high order bits of rand() by calculating the high value of the range with RAND_MAX and then dividing the call to rand() by the result. The point where 1 is added to RAND_MAX is important to note, this forces the range of random numbers to be 1 through 10 instead of 0 through 9.Code:#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand ( (unsigned int)std::time ( 0 ) );
std::cout<< std::rand() / ( RAND_MAX / 10 + 1 ) <<std::endl;
std::cout<< (int)( (double)std::rand() / ( RAND_MAX + 1 ) * 10 ) <<std::endl;
return 0;
}
rand() / (RANDMAX / 10 + 1)
Let's suppose RANDMAX is 500. If rand() returns 1, then the result is:
1 / (500 / 10 + 1) = 1/51
which because of integer arithmetic produces 0. As a consequence, if rand() returns any number less than 51, the answer is 0, and it creates the mapping:
0 - 50 ---> 0
If rand() returns 51, then the result is 1. Due to integer arithmetic, the result will continue to be 1 until the numerator reaches 102, giving this mapping:
0 - 50 -----> 0
51 - 101 --> 1
If you continue figuring out the ranges, you will come up with this:
0 - 50 -----> 0
51 - 101 --> 1
102 - 152 -> 2
153 - 203 -> 3
204 - 254 -> 4
..
..
..
459 - 500 -> 9
First of all, you can see that the numbers produced are 0-9, not 1-10 as the tutorial seems to imply. In addition, all the ranges of numbers contain 51 numbers except the range 459 - 500, which contains only 42 numbers. That means the number 9 is less likely to be produced by the calculation, which means the calculation will not produce random numbers between 0 and 9.
The second method seems to suffer from similar problems. If RAND_MAX is equal to 500 and rand() returns 1, then the calculation produces:
1.0 / 501 * 10 = .02
and when you cast that to an int, you get 0.
The ranges are a little better, but the first range has 51 numbers, while the other ranges have 50 numbers. That makes it more likely the number 0 will be produced over any other number.
0 - 50 -----> 0
51 - 100 --> 1
101 - 150 -> 2
151 - 200 -> 3
201 - 250 -> 4
..
..
..
451 - 500 -> 9
Also, when I test out the code, I get the same number everytime, which must mean the seed is the same everytime I run the code. Why doesn't that work?