Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nan and inf in C?

Tags:

c

math

nan

infinity

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.

like image 943
Graphics Noob Avatar asked Dec 17 '09 18:12

Graphics Noob


People also ask

What is the difference between NaN and INF?

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 .

What value is Inf in C?

Inf means infinity, and is the result of dividing a positive number by zero -- e.g., 1/0 → Inf.

What is NaN in C?

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).


1 Answers

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

like image 85
Alok Singhal Avatar answered Sep 20 '22 18:09

Alok Singhal