【问题标题】:Floating-point overflows to negative浮点溢出为负
【发布时间】:2018-02-17 23:50:04
【问题描述】:

我们知道有符号整数可能会发生整数溢出,例如,符号位从 0 翻转到 1,导致正整数变为负数。

浮点数也会发生同样的情况吗?实验上,当数字太大时,它会变成Inf。但是会不会溢出尾数或者指数,导致类似的问题?

【问题讨论】:

    标签: floating-point numbers precision floating-accuracy integer-overflow


    【解决方案1】:

    在 IEEE 类型浮点(浮点 32 位、双精度 64 位、长双精度 80 位)的情况下,数字的存储方式类似于符号 + 幅度而不是二进制补码。指数也没有正常范围,具有零或全一位的特殊值。双倍的维基文章:

    https://en.wikipedia.org/wiki/Double-precision_floating-point_format

    如果对不包含特殊值情况(如无穷大、NAN、...)的浮点类型数组执行基数排序等操作,通常会使用从符号和大小到“二进制补码”的转换。示例 C 宏,用于在 64 位符号和幅度之间转换为 unsigned long long(64 位无符号整数)并返回。请注意,这会导致转换后的负零的符号和幅度值小于正零的值。

    // converting doubles to unsigned long long for radix sort or something similar
    // note -0 converted to 0x7fffffffffffffff, +0 converted to 0x8000000000000000
    // -0 is unlikely to be produced by a float operation
    
    #define SM2ULL(x) ((x)^(((~(x) >> 63)-1) | 0x8000000000000000ull))
    #define ULL2SM(x) ((x)^((( (x) >> 63)-1) | 0x8000000000000000ull))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多