Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...