需要对随机函数迅速进行解释 [英] 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'
-
我的代码是
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.
提前谢谢!
推荐答案
一个 IEEE 754 32位浮点数字的尾数有24个有效位,不足以精确存储10位整数:
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)
仍然是0.0到1.0之间的浮点数.将计算更改为
is still a floating point number between 0.0 and 1.0. Changing the calculation to
return CGFloat(arc4random()) / 0xFFFFFFFF
将在64位平台上修复该警告:整数常量现在转换为(64位)Double
.
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)
}
这篇关于需要对随机函数迅速进行解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!