Inspired by General purpose random number generation I decided to perform my own tests to see what was wrong with rand(). Using this program:
srand(time(0));
for (int i = 0; i < 1000000; ++i)
{
std::cout << rand() % 1000 << " ";
}
I loaded it up in Octave using the commands:
S = load("test.txt")
hist(S)
And got this result:
To me the results seem to be pretty uniform. I expected the results to be more skewed. Did I conduct my test wrong?
The test in your question doesn't really test for randomness. All it does is ensure that the numbers are uniformly distributed. This is a necessary but not a sufficient condition: there are many other ways in which a random number generator can be deficient.
For example, if I gave your a function that returned the numbers 0, 1, 2, ..., 999 in a loop, it would also pass your test. Yet it would clearly fail any reasonable definition of randomness.
To see how random number generators are tested in practice, take a look at
For a discussion of rand()
specifically, check out rand()
Considered Harmful.
One important point you aren't considering is how predictable the generated random sequence is. When using time() as the randomness seed, if the attacker knows - more or less - when the seed was generated, he can rather easily reproduce your entire random sequence.
This is why a true random source is desired, assuming you use these random numbers for anything security-related.
When security really matters, you further want to get each of your numbers from the true random source, without relying on a PRNG at all. Slower but safer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With