Precision of multiplication by 1.0 and int to float conversion(乘以 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
是准确的.可能不是从 int
到 float
的转换.
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 到浮点转换的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:乘以 1.0 和 int 到浮点转换的精度


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01