乘以 1.0 和 int 到浮点转换的精度 [英] Precision of multiplication by 1.0 and int to float conversion

查看:39
本文介绍了乘以 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.

这篇关于乘以 1.0 和 int 到浮点转换的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆