且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rand() 生成相同的数字——即使在我的主要内容中有 srand(time(NULL)) !

更新时间:2023-02-03 12:20:14

问题是随机数生成器的种子值非常接近 - 程序的每次运行只会改变时间的返回值() 少量 - 可能是 1 秒,甚至可能没有!相当差的标准随机数生成器然后使用这些相似的种子值来生成明显相同的初始随机数.基本上,您需要一个比 time() 更好的初始种子生成器和一个比 rand() 更好的随机数生成器.

The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to generate apparently identical initial random numbers. Basically, you need a better initial seed generator than time() and a better random number generator than rand().

我认为实际使用的循环算法是从 Accelerated C++ 中提取的,旨在在所需范围内产生更好的数字分布,而不是使用 mod 运算符.但它无法弥补总是(有效地)给予相同的种子.

The actual looping algorithm used is I think lifted from Accelerated C++ and is intended to produce a better spread of numbers over the required range than say using the mod operator would. But it can't compensate for always being (effectively) given the same seed.