drand48() 总是 returns 相同的值

drand48() always returns same value

drand48() 在我关闭应用程序并再次打开后总是 returns 相同的值

当我调用 drand48() 并打印出结果时,它在关闭和打开应用程序后始终相同。

有谁知道如何防止这种情况发生并每次都获得一个没有可预测模式的随机数?

非常感谢

这似乎并不意外。引用自 here(强调我的):

The srand48(), seed48() and lcong48() are initialisation entry points, one of which should be invoked before either drand48(), lrand48() or mrand48() is called. (Although it is not recommended practice, constant default initialiser values will be supplied automatically if drand48(), lrand48() or mrand48() is called without a prior call to an initialisation entry point.)

因此,如果您在使用 PRNG 之前不对其进行播种,您将获得恒定的种子,这意味着您每次都会获得完全相同的序列。

请注意,您通常应该只播种一次,在您的情况下可能是在启动时,并且永远不要在您还使用数字的循环中。

drand48 创建伪随机数序列。您需要每隔 运行 设置一个不同的种子。

像这样

let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand48(Int(time)) let number = drand48 ()