Reputation: 1523
I see a very strange behavior when using rand() in c++. Here is my code.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <limits.h>
#define N 10
int main() {
srand(time(NULL));
while(true) {
int i = N * ((double) rand() / (RAND_MAX));
//std::cout << i << std::endl; // If there is any code here, everything goes fine.
if (i == N) {
std::cout << "i " << i << " should never happen" << std::endl;
} else {
std::cout << ".";
}
}
}
Here is the output:
i 10 should never happen
i 10 should never happen
i 10 should never happen
...
It really doesn't make sense to me because I think i will never ever be 10. The strange thing is that it works perfectly fine if I try any of the following:
My compiler is mingw32-g++.exe (TDM-2 mingw32) 4.4.1.
This really confuses me, could anyone tell me what's going on?
Upvotes: 1
Views: 339
Reputation: 354864
This is to be expected:
The
rand()
function returns a pseudo-random integer in the range 0 toRAND_MAX
inclusive (i.e., the mathematical range [0,RAND_MAX
]).
So rand() / RAND_MAX
can be 1 because the range is inclusive. Your fix with RAND_MAX + 1
is usually the option that is taken.
That being said, there are better options to generate random numbers in a range that will yield a uniform distribution.
Upvotes: 3