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

1

4

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!

Huston answered 28/12, 2015 at 9:13 Comment(0)
B
4

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.

Bumbledom answered 28/12, 2015 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.