c – 调用srand如何不止一次影响随机性的质量?

c – 调用srand如何不止一次影响随机性的质量?,第1张

概述这 comment,其中指出: srand(time(0)); I would put this line as the first line in main() instead if calling it multiple times (which will actually lead to less random numbers). ……我已经加粗了我遇到问题的路线…重复一般建议,在程序中拨打 这 comment,其中指出:

srand(time(0)); I would put this line as the first line in main()
instead if calling it multiple times (which will actually lead to less
random numbers).

……我已经加粗了我遇到问题的路线…重复一般建议,在程序中拨打srand一次.像srand() — why call only once?这样的问题重新迭代,因为time(0)以秒为单位返回当前时间,在同一秒内多次调用srand将产生相同的种子.常见的解决方法是使用毫秒或纳秒.

但是,我不明白为什么这意味着srand应该或者只能被调用一次,或者它如何导致更少的随机数.

cppreference:

Generally speaking,the pseudo-random number generator should only be
seeded once,before any calls to rand(),and the start of the program.
It should not be repeatedly seeded,or reseeded every time you wish to generate a new batch of pseudo-random numbers.

phoxis对srand() — why call only once?的回答:

Initializing once the initial state with the seed value will generate
enough random numbers as you do not set the internal state with srand,
thus making the numbers more probable to be random.

也许他们只是使用不精确的语言,没有一个解释似乎解释了为什么多次调用srand是坏的(除了生成相同的随机数序列)或它如何影响数字的“随机性”.有人可以为我清楚这一点吗?

解决方法 std :: time(0)函数以秒为单位返回时间.

问题是如果你每次要求一个随机数std时调用std :: srand(),那么计算机速度很快,std :: time(0)函数在调用std :: srand()之间不会改变: :srand()将继续被重置以产生相同的数字序列,直到std :: time()函数返回不同的时间(一秒后).

在一秒钟内,您最终可以生成相同数量的数百万次!这不是很随机.

总结

以上是内存溢出为你收集整理的c – 调用srand如何不止一次影响随机性的质量?全部内容,希望文章能够帮你解决c – 调用srand如何不止一次影响随机性的质量?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1246405.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存