将 double 转换为 float 时会发生什么?
What happens when casting double to float?
假设最接近双精度值 d
的浮点值是 f1
和 f2
,因此 f1
< d
< f2
.在 C99 中将 d
转换为 float 的结果是什么? f1
还是 f2
?考虑这两种情况:
- 如果
d - f1 > f2 - d
- 如果
d - f1 < f2 - d
我假设 d 本身不能用任何浮点值精确表示。
C 2018 6.3.1.5 讨论了实际浮点类型之间的转换并说:
… If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.
默认情况下,常见的 C 实现使用舍入到最近的值,四舍五入到具有偶数位的候选者。
舍入模式由FLT_ROUNDS
报告,在<float.h>
中声明并在5.2.4.2.2 9:
中指定
The rounding mode for floating-point addition1 is characterized by the implementation-defined value of FLT_ROUNDS:
−1 indeterminable
0 toward zero
1 to nearest
2 toward positive infinity
3 toward negative infinity
循环模式可能会被 <fenv.h>
中声明的 fesetround
函数改变,尽管对它的支持和它需要的 FENV_ACCESS
编译指示参差不齐。
C 标准还提供了 C 实现可能采用的附件 F。在这种情况下,编译和执行期间的默认舍入模式是根据 F.8.2 1:
舍入到最近的偶数
During translation the IEC 60559 default modes are in effect:
— The rounding direction mode is rounding to nearest…
和 F.8.3 1:
At program startup the floating-point environment is initialized as prescribed by IEC 60559:
…
— The rounding direction mode is rounding to nearest.
我的理解是 IEC 60559 在功能上等同于 IEEE 754。
脚注
1 我怀疑“加法”是标准中的一个错误,本意是“算术”。
假设最接近双精度值 d
的浮点值是 f1
和 f2
,因此 f1
< d
< f2
.在 C99 中将 d
转换为 float 的结果是什么? f1
还是 f2
?考虑这两种情况:
- 如果
d - f1 > f2 - d
- 如果
d - f1 < f2 - d
我假设 d 本身不能用任何浮点值精确表示。
C 2018 6.3.1.5 讨论了实际浮点类型之间的转换并说:
… If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.
默认情况下,常见的 C 实现使用舍入到最近的值,四舍五入到具有偶数位的候选者。
舍入模式由FLT_ROUNDS
报告,在<float.h>
中声明并在5.2.4.2.2 9:
The rounding mode for floating-point addition1 is characterized by the implementation-defined value of FLT_ROUNDS:
−1 indeterminable
0 toward zero
1 to nearest
2 toward positive infinity
3 toward negative infinity
循环模式可能会被 <fenv.h>
中声明的 fesetround
函数改变,尽管对它的支持和它需要的 FENV_ACCESS
编译指示参差不齐。
C 标准还提供了 C 实现可能采用的附件 F。在这种情况下,编译和执行期间的默认舍入模式是根据 F.8.2 1:
舍入到最近的偶数During translation the IEC 60559 default modes are in effect:
— The rounding direction mode is rounding to nearest…
和 F.8.3 1:
At program startup the floating-point environment is initialized as prescribed by IEC 60559:
…
— The rounding direction mode is rounding to nearest.
我的理解是 IEC 60559 在功能上等同于 IEEE 754。
脚注
1 我怀疑“加法”是标准中的一个错误,本意是“算术”。