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

我的未来我决定 提交于 2019-12-01 05:38:52

问题


I'm new to Swift and just saw this code used to generate a random angle degree in a tutorial.

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

I'm wondering is the line return CGFloat(Float(arc4random()) / 0xFFFFFFFF) generates a random float number between 0 and 1.0? Then why cannot just use drand()? Any difference between the two functions? Thanks!


回答1:


drand48() is fine for lots of applications, but is insecure (in other words predictable). arc4random() while not perfect was designed with security in mind.

I think Apple pushes people to arc4random() because of that. So, to answer your question: if you are generating random numbers to simulate something, drand48 should be fine, but if you are generating random numbers to protect something, then use arc4random() (or something even more secure like SecRandomCopyBytes()).


From ONLamp's 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.



来源:https://stackoverflow.com/questions/34490662/why-use-floatarc4random-0xffffffff-instead-of-drand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!