为什么使用 Float(arc4random()) / 0xFFFFFFFF 而不是 drand()

Why use Float(arc4random()) / 0xFFFFFFFF instead of drand()

我是 Swift 的新手,刚刚在教程中看到这段代码用于生成随机角度。

func random() ->CGFloat{
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max:CGFloat) ->CGFloat{
    return random()*(max-min)+min
}

我想知道 return CGFloat(Float(arc4random()) / 0xFFFFFFFF) 行是否生成了一个介于 0 和 1.0 之间的随机浮点数?那为什么不能只使用 drand() 呢?这两个函数之间有什么区别吗?谢谢!

drand48() 适用于许多应用程序,但不安全(换言之可预测)。 arc4random()not perfect 在设计时就考虑到了安全性。

我认为 Apple 正因为如此将人们推向 arc4random()。所以,回答你的问题:如果你生成随机数来模拟某些东西,drand48 应该没问题,但如果你生成随机数来保护某些东西,那么使用 arc4random()(或者更安全的东西喜欢 SecRandomCopyBytes()).


来自 ONLamp 的 Secure Programming Techniques:

drand48( ), lrand48( ), and mrand48( )

The drand48( ) function is one of many functions that make up the System V random number generator. According to the Solaris documentation, the algorithm uses "the well-known linear congruential algorithm and 48-bit integer arithmetic." The function drand48( ) returns a double-precision number that is greater than or equal to 0.0 and less than 1.0, while the lrand48( ) and mrand48( ) functions return random numbers within a specified integer range. As with random( ), these functions provide excellent random numbers for simulations and games, but should not be used for security-related applications such as picking cryptographic keys or simulating one-time pads; linear congruential algorithms are too easy to break.