C - 添加两个单精度浮点正常数,不能得到无穷大的结果

标签 c floating-point ieee-754 single-precision

我在玩浮点运算,遇到了一些需要解释的事情。

将舍入模式设置为“接近零”时,又名:

fesetround(FE_TOWARDZERO);

加上不同种类的正常正数,我永远无法达到无穷大。

但是,从 ieee 745 中得知,将有限数相加会导致溢出到无穷大。

例如:

#include <fenv.h>
#include <stdio.h>

float hex2float (int hex_num) {
  return *(float*)&hex_num;
}

void main() {
  int a_int = 0x7f7fffff; // Maximum finite single precision number, about 3.4E38
  int b_int = 0x7f7fffff;
  float a = hex2float(a_int);
  float b = hex2float(b_int);
  float res_add;

  fesetround(FE_TOWARDZERO);  // need to include fenv.h for that
  printf("Calculating... %+e + %+e\n",a,b);
  res_add = a + b;
  printf("Res = %+e\n",res_add);
}

但是,如果我将舍入模式更改为其他模式,我可能会得到 +INF 作为答案。

Can someone explain this?

最佳答案

对观察到的行为的解释是,它是由 IEEE 754-2008 浮点标准强制执行的:

7.4 Overflow

The overflow exception shall be signaled if and only if the destination format’s largest finite number is exceeded in magnitude by what would have been the rounded floating-point result (see 4) were the exponent range unbounded. The default result shall be determined by the rounding-direction attribute and the sign of the intermediate result as follows:

[...]

b) roundTowardZero carries all overflows to the format’s largest finite number with the sign of the intermediate result.

因此对于此处使用的舍入模式(截断,或向零舍入),溢出情况下的结果是最大的有限数,不是无穷大。

关于C - 添加两个单精度浮点正常数,不能得到无穷大的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37439180/

相关文章:

floating-point - 如何用 nom 解析完整的 f32?

c++ - float 的验证和转换

C++ ofstream浮点编码

c++ - while循环中的浮点比较与模数

floating-point - IEEE754 : guarantees on division results

java - 为什么我的 float 被截断?

c - 当我在代码中没有看到错误时,我无法将示例数据加载到文件中

c - 如何查看输入文件的第一个字符是否为数字? C编程

java - 从 Java 使用 C# 编写的 DLL

c - 在 C 中取消引用指向不完整类型错误的指针