乘以 1.0 和 int 到浮点转换的精度

假设条件 (int)(i * 1.0f) == i 对于任何整数 i 为真是否安全?

Is it safe to assume that the condition (int)(i * 1.0f) == i is true for any integer i?

推荐答案

没有.

如果 i 足够大以至于 int(float(i)) != i (假设 float 是 IEEE-754 单精度,i = 0x1000001 足以证明这一点)那么这是错误的,因为乘以 1.0f 会强制转换为 float,即使随后的乘法不会改变值.

If i is sufficiently large that int(float(i)) != i (assuming float is IEEE-754 single precision, i = 0x1000001 suffices to exhibit this) then this is false, because multiplication by 1.0f forces a conversion to float, which changes the value even though the subsequent multiplication does not.

但是,如果 i 是一个 32 位整数并且 double 是 IEEE-754 double,那么 是真的 int(i*1.0) == i.

However, if i is a 32-bit integer and double is IEEE-754 double, then it is true that int(i*1.0) == i.

为了完全清楚,乘以 1.0f 是准确的.可能不是从 intfloat 的转换.

Just to be totally clear, multiplication by 1.0f is exact. It's the conversion from int to float that may not be.

相关文章