Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swift5

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?

like image 256
dengST30 Avatar asked Apr 07 '19 15:04

dengST30


1 Answers

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)
like image 142
OOPer Avatar answered Oct 09 '22 05:10

OOPer