Madifie
Madifie

Reputation: 35

Need explanation about random function swift

Got a question about my random function: why is it giving this error?

'4294967295' is not exactly representable as 'Float'; it becomes '4294967296'

-

my code is

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

it doesn't change the functionality of the application but it just appeared out of nowhere.

thanks in advance!

Upvotes: 3

Views: 277

Answers (1)

Martin R
Martin R

Reputation: 539965

A IEEE 754 32-bit floating point number has 24 significant bits for the mantissa, that is not enough to store a 10-digit integer exactly:

print(0xFFFFFFFF)             // 4294967295
print(Float(0xFFFFFFFF))      // 4.2949673e+09
print(Int(Float(0xFFFFFFFF))) // 4294967296

That won't affect your code because

Float(arc4random()) / Float(0xFFFFFFFF)

is still a floating point number between 0.0 and 1.0. Changing the calculation to

return CGFloat(arc4random()) / 0xFFFFFFFF

will fix the warning on 64-bit platforms: The integer constant is now converted to a (64-bit) Double.

But as of Swift 4.2 you can avoid the problem completely by using the new Random API:

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return CGFloat.random(in: min...max)
}

Upvotes: 9

Related Questions