Swift randomFloat issue: '4294967295' is not exactly representable as 'Float'

4

When generating a random CGFloat, I use the following code. Some explanation here

extension CGFloat{
     static func randomFloat(from:CGFloat, to:CGFloat) -> CGFloat {
          let randomValue: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
          return randomValue * (to - from ) + from
      } 
}

It used to be OK. Works fine now.

There is a warning, after I upgraded to Swift 5.

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

to the line of code

let randomValue: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)

How to fix it?

swift
swift5
asked on Stack Overflow Apr 7, 2019 by dengST30 • edited Apr 7, 2019 by Sulthan

2 Answers

7

Simplest solution: abandon your code and just call https://developer.apple.com/documentation/coregraphics/cgfloat/2994408-random.

answered on Stack Overflow Apr 7, 2019 by matt
5

As you know Float has only 24-bits of significand, so 32-bit value 0xFFFFFFFF would be truncated. So, Swift is warning to you that Float cannot represent the value 0xFFFFFFFF precisely.

The short fix would be something like this:

let randomValue: CGFloat = CGFloat(Float(arc4random()) / Float(0xFFFFFFFF))

With using Float.init explicitly, Swift would not generate such warnings.


But the preferred way would be using random(in:) method as suggested in matt's answer:

return CGFloat(Float.random(in: from...to))

or simply:

return CGFloat.random(in: from...to)
answered on Stack Overflow Apr 7, 2019 by OOPer

User contributions licensed under CC BY-SA 3.0