Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is rand() really that bad?

Tags:

c++

random

c++11

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:

result

To me the results seem to be pretty uniform. I expected the results to be more skewed. Did I conduct my test wrong?

like image 638
user4156679 Avatar asked Oct 18 '14 13:10

user4156679


2 Answers

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

  • http://csrc.nist.gov/groups/ST/toolkit/rng/documents/nissc-paper.pdf
  • http://www.random.org/analysis/
  • http://www.random.org/analysis/Analysis2005.pdf

For a discussion of rand() specifically, check out rand() Considered Harmful.

like image 103
NPE Avatar answered Sep 28 '22 02:09

NPE


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.

like image 27
Hexagon Avatar answered Sep 28 '22 02:09

Hexagon