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

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c++ - Is rand() really that bad?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...