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

标签 swift random cgfloat

我是 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 之间的随机 float ?那为什么不能只使用 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.

关于swift - 为什么使用 Float(arc4random())/0xFFFFFFFF 而不是 drand(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34490662/

相关文章:

ios - self.locationManager.requestAlwaysAuthorization() 仅适用于 iOS 8.0 或更高版本 - Swift

swift - Xcode - Swift 计算属性的奇怪代码覆盖率

oracle - 如何使用 PL/SQL 在 Oracle 中创建具有随机字段数的表?

python - 在 Python 中生成随机文件名的最佳方法

xcode - Swift 表达式太复杂,无法在合理的时间内解决

iphone - 如何将 CGFloat 设置为 UILabel 的文本属性

Swift 枚举原始值 : not working with CGFloat = -1. 0

swift - 具有子类类型的类方法调用闭包的基类

ios - 使用 nscoder 对自定义对象进行编码并保存到 nsuserdefaults 是否已加密?

c - "Chances"函数发生吗?