Need explanation about random function swift

3

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!

swift
random
asked on Stack Overflow Mar 29, 2019 by Madifie

1 Answer

7

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)
}
answered on Stack Overflow Mar 29, 2019 by Martin R • edited Mar 29, 2019 by Martin R

User contributions licensed under CC BY-SA 3.0