Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a 32 bit normalized floating point number that hasn't been operated on, same on any platform/compiler?

For example:

float a = 3.14159f;

If I was to inspect the bits in this number (or any other normalized floating point number), what are the chances that the bits are different in some other platform/compiler combination, or is that possible?

like image 239
KJS Avatar asked Apr 25 '16 17:04

KJS


2 Answers

Not necessarily: The c++ standard doesn't define floating point representation (it doesn't even define the representation of signed integers), although most platforms probably orient themselves on the same IEEE standard (IEEE 754-2008?).

like image 163
MikeMB Avatar answered Oct 08 '22 19:10

MikeMB


Your question can be rephrased as: Will the final assertion in the following code always be upheld, no matter what platform you run it on?

#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);
}

Answer: There's nothing in the C++ standard that guarantees that the assertion will be upheld. Yet, on most sane platforms the assertion will hold and the code won't abort, no matter if the platform is big- or little-endian. As long as you only care that your code works on some known set of platforms, it'll be OK: you can verify that the tests pass there :)

Realistically speaking, some compilers might use a sub-par decimal-to-IEEE-754 conversion routine that doesn't properly round the result, so if you specify f to enough digits of precision, it might be a couple of LSBs of mantissa off from the value that would be nearest to the decimal representation. And then the assertion won't hold anymore. For such platforms, you might wish to test a couple mantissa LSBs around the desired one.

like image 28
Kuba hasn't forgotten Monica Avatar answered Oct 08 '22 19:10

Kuba hasn't forgotten Monica