Precision of multiplication by 1.0 and int to float conversion

后端 未结 4 1038
一个人的身影
一个人的身影 2020-12-16 08:53

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

4条回答
  •  隐瞒了意图╮
    2020-12-16 09:36

    No.

    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.

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


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

提交回复
热议问题