Home > Blockchain >  How to detect non IEEE-754 float, and how to use them?
How to detect non IEEE-754 float, and how to use them?

Time:04-28


Hi,
I'm writing classes for basic types, so that code is logicly the same on multiple platforms and compilators (like int_least16_t for int). For fun! (I'm still a student)
And I read this:

float [...] Matches IEEE-754 binary32 format if supported.

And what's worse:

Floating-point types MAY support special values: , NaN or -0

Which means that float MAY be unsigned...

I know it's like with __int128, and standard is just a standard, but still...
IEEE-754 is from 1985, but same machines can be weird, and same legacy hardware doesn't have a floating unit.

As I understand, float is mendatory (not optional like int16_t), but can be in any standart, and any set of values can be posible?


Only thing we heve are same macros(<cfloat>):

  • FLT_MIN, FLT_MAX - Even if FLT_MIN = IEEE-754::FLT_MIN, float can be non IEEE-754. For egzample float with: fliped exponent with fraction...

  • FLT_RADIX - Base system? If so, can help to write the exact value. But still float can be 3 bit or 200 bit (in size)...

  • FLT_EPSILON - (from 1 to next) We might use it (with base) to check fraction size...

  • FLT_MANT_DIG - Is it "mantisa" digits / fraction size?

  • FLT_MAX_EXP - Exponent filled with 1... in IEEE-754, but outside can be a random number?

If float is like IEEE-754 (sign,exponent,fraction), then it's easy, but if -0 and NaN are optional then it MAY be difrent. Because I can't tell them apart, I can't use bit representation (in safe manner). And if is optional float is no longer safe type.

The only way out I see is to add makro to compiler.

I know it's theoretical problem, but I'm intrested if there is any check posible or We all write implementation dependend code, when We use float keyword?

CodePudding user response:

In C , the value of std::numeric_limits<T>::is_iec559 shall be true for all floating-point types T "if, and only if, the type adheres to ISO/IEC/IEEE 60559" and ISO/IEC/IEEE 60559:2011 is the same as IEEE 754-2008, so:

#include <iostream>
#include <limits>

int main() {
    std::cout << std::boolalpha << std::numeric_limits<float>::is_iec559 << '\n';
}

Note: As noted in the comments, some implementations may still report true for this constant event though their floating point types are not following the IEEE 754-2008 standard to the letter.

For example, in gcc, you can compile with the options -Ofast or -ffast-math which in turn sets a number of options which can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions.

  • Related