是否是32位标准化浮点数,尚未运行,在任何平台/编译器上都是相同的?

KJS*_*KJS 3 c++ floating-point floating-accuracy

例如:

float a = 3.14159f;
Run Code Online (Sandbox Code Playgroud)

如果我要检查这个数字中的位(或任何其他标准化的浮点数),那么在某些其他平台/编译器组合中这些位的可能性有多大,或者可能?

Mik*_*eMB 8

不一定:c ++标准没有定义浮点表示(它甚至没有定义有符号整数的表示),尽管大多数平台可能都定位于相同的IEEE标准(IEEE 754-2008?).


Rei*_*ica 6

您的问题可以改为:以下代码中的最终断言是否始终得到维护,无论您在哪个平台上运行它?

#include <cassert>
#include <cstring>
#include <cstdint>
#include <limits>
#if __cplusplus < 201103L // no static_assert prior to C++11
#define static_assert(a,b) assert(a)
#endif
int main() {
  float f = 3.14159f;
  std::uint32_t i = 0x40490fd0;// IEC 659/IEEE 754 representation
  static_assert(std::numeric_limits<float>::is_iec559, "floating point must be IEEE 754");
  static_assert(sizeof(f) == sizeof(i), "float must be 32 bits wide");
  assert(std::memcmp(&f, &i, sizeof(f)) == 0);
}
Run Code Online (Sandbox Code Playgroud)

答:C++标准中没有任何内容可以保证断言得到维护.然而,在大多数理智的平台上,无论平台是大端还是小端,断言都会成立并且代码不会中止.只要您只关心您的代码在某些已知的平台上工作,它就可以了:您可以验证测试是否通过那里:)

实际上,一些编译器可能会使用一个小数到十进制到IEEE-754的转换例程,它不能正确地舍入结果,所以如果你指定f了足够的精度数字,那么它可能是一些LSB的尾数.最接近十进制表示的值.然后断言将不再存在.对于这样的平台,您可能希望测试所需的几个尾数LSB.