rand()真的那么糟糕吗? [英] Is rand() really that bad?

查看:199
本文介绍了rand()真的那么糟糕吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受到通用随机数生成的启发,我决定执行自己的测试以看看rand()出了什么问题.使用此程序:

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 << " ";
}

我使用以下命令将其加载到Octave中:

I loaded it up in Octave using the commands:

S = load("test.txt")
hist(S)

并得到以下结果:

对我来说,结果似乎非常一致.我希望结果会更偏斜.我的考试做错了吗?

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.

例如,如果我为您提供了一个循环返回数字0、1、2,...,999的函数,则该函数也将通过您的测试.然而,它显然将无法对随机性做出任何合理的定义.

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

要专门讨论rand(),请查看 rand()被认为有害.

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

这篇关于rand()真的那么糟糕吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆