Portable check for infinity and non-number

I am looking for something that does not use assumptions regarding the implementation of a floating point type and does not use C ++ 11 / C99 methods.

Is the following code a reliable verification method for INF and NAN? If not, what exactly could go wrong?

bool isfinite(double n) { if(std::numeric_limits<double>::has_infinity) { double inf = std::numeric_limits<double>::infinity(); if(std::memcmp(&n, &inf, sizeof(double)) == 0) return false; double neginf = -inf; if(std::memcmp(&n, &neginf, sizeof(double)) == 0) return false; } if(std::numeric_limits<double>::has_quiet_NaN) { double nan = std::numeric_limits<double>::quiet_NaN(); if(std::memcmp(&n, &nan, sizeof(double)) == 0) return false; double negnan = -nan; if(std::memcmp(&n, &negnan, sizeof(double)) == 0) return false; } return true; } 

Edit: In particular, I am looking for a way to accomplish this within a language and not rely on internal compiler functions, a priori definitions, or other libraries such as boost.

+7
c c ++ 98
source share
1 answer

Confident OP code does not always work.

A double (for example, IEEE 754 ) has a unique binary representation of NaN:
( s is the sign bit.)

 s1111111 1111baaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa 

Where not all baa ... aaa is 0. (if baa ... aaa is all 0, then this is INF .) The difference between quiet NaN and NaN signaling is often indicated by b .

A significant problem is that not all NaNs have the same bit pattern. The testing proposed for double for a single bit pattern is insufficient to detect NaN.

Instead, propose a portable test that does not rely on NaN, as well as an Infinity existing on this C platform.

 double x; // NAN are never arithmetically equal, even to themselves. if (x != x) NaN_Detected(); if (x > DBL_MAX || x < -DBL_MAX) Inf_Detected(); 

[Edit] compare patch: thanks @Jongware

+4
source share

All Articles