据我所了解,
arc4random()
生成的随机数要比 rand()
生成的随机数好得多,但是我还没有找到种子的方法,我想像使用 srand()
一样使用它。有办法吗?arc4random()
生成的随机数要比 rand()
生成的随机数好得多,但是我还没有找到种子的方法,我想像使用 srand()
一样使用它。有办法吗?arc4random的设计并非如此。正如文档所述:
arc4random()
函数可以快速提供高质量的32位伪随机数。arc4random()
会定期从内核强随机数子系统(random(4)
)中获取种子。
由于它已经从熵源重新进行了种子生成,因此手动设置种子没有任何意义,实际上这种方法不存在。
arc4random
会从中重新生成种子。然而,这已经被弃用,并且你仍然无法控制种子生成。这基本上意味着你不能将 arc4random
视为一个 PRNG,即当使用相同的初始化向量进行种子化时,它会产生完全相同的序列。java.security.SecureRandom
存在同样的“问题”,这也是设计如此。如果需要对 PRNG 进行细粒度控制,则可以实现 MT-19937,它的 C 源代码很短,而且可轻松获得。 - Joeyarc4random
的种子,它也无济于事,因为它会定期重新生成种子,所以再现性已经消失了。 - Joey在iOS 9中,您实际上可以做到这一点。
import GameKit
let source = GKARC4RandomSource(seed: "hello world".data(using: .utf8)!)
source.dropValues(1024)
source.nextInt() // <-- your number
!
)和相同数量的删除值,就会得到相同的结果。在Swift 3中,当我需要一个种子值时,我使用srand48()
和drand48()
。我创建了这个函数,它似乎对我的需求足够好:
func seeded_rand(seed:Int, min:Double, max:Double) -> Int
{
srand48(seed)
return Int(round(drand48() * (max-min)) + min)
}
您可以使用arc4random_addrandom()
将字节序列添加为随机性到arc4random中。
你实际上不需要手动进行种子操作... 它会在第一次调用时自动进行。通过调用文档来查看更多信息。
man arc4random
在你的shell中,相关的行,在DESCRIPTION下面:
There is no need to call arc4random_stir() before using arc4random(),
since arc4random() automatically initializes itself.