I have a numerical method that could return nan or inf if there was an error, and for testing purposed I'd like to temporarily force it to return nan or inf to ensure the situation is being handled correctly. Is there a reliable, compiler-independent way to create values of nan and inf in C?
After googling for about 10 minutes I've only been able to find compiler dependent solutions.
inf is infinity - a value that is greater than any other value. -inf is therefore smaller than any other value. nan stands for Not A Number, and this is not equal to 0 .
Inf means infinity, and is the result of dividing a positive number by zero -- e.g., 1/0 → Inf.
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).
You can test if your implementation has it:
#include <math.h> #ifdef NAN /* NAN is supported */ #endif #ifdef INFINITY /* INFINITY is supported */ #endif
The existence of INFINITY
is guaranteed by C99 (or the latest draft at least), and "expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time."
NAN
may or may not be defined, and "is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN."
Note that if you're comparing floating point values, and do:
a = NAN;
even then,
a == NAN;
is false. One way to check for NaN would be:
#include <math.h> if (isnan(a)) { ... }
You can also do: a != a
to test if a
is NaN.
There is also isfinite()
, isinf()
, isnormal()
, and signbit()
macros in math.h
in C99.
C99 also has nan
functions:
#include <math.h> double nan(const char *tagp); float nanf(const char *tagp); long double nanl(const char *tagp);
(Reference: n1256).
Docs INFINITY Docs NAN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With