C/C++ Nan Constant (Literal)

C/C++ NaN constant (literal)?

In C, NAN is declared in <math.h>.

In C++, std::numeric_limits<double>::quiet_NaN() is declared in <limits>.

But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan() from <math.h> in C, or std::isnan() from <cmath> in C++.

NaN Literal in C?

In C99's <math.h>

  7.12  Mathematics <math.h>
   [#5] The macro

NAN

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

How to use nan and inf in C?

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

How to produce a NaN float in c?

Using floating point numbers, 0.0 / 0.0 isn't a "divide by zero" error; it results in NaN.

This C program prints -nan:

#include <stdio.h>

int main()
{
float x = 0.0 / 0.0;
printf("%f\n", x);
return 0;
}

In terms what NaN looks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.

How to define NaN value in ANSI C?

NaN isn't an "abstract type". It's a value of a floating-point datum.

If by "ANSI C" you mean standard C (which is the actual meaning of the term, in as much as it has one), include <math.h> and use the NAN macro to produce a nan, and isnan(x) to detect one.

If by "ANSI C" you actually mean the long-replaced C89 standard (which some people intend, even if it isn't formally correct), you can produce a NaN value with 0./0., and check for one with x != x.

In C++, is exactly one of , == and guaranteed to be true on floats?

No.

It's enough for either a or b to be NaN for each of a < b, a == b and a > b to be false.

If both a and b are non-NaN then exactly one of a < b, a == b or a > b has to be true.

In complement, this answer tells you how you can get a NaN value in C++ (there are several NaN values, that can be distinguished by inspecting their representations; they are all different from each other because NaN is never equal to anything,) and how you can test whether a value is a NaN (an idiomatic test to see if a variable x is a NaN is x != x, and indeed std::isnan() is often implemented this way, but some programmers who will have to read your code may be confused by it).

And then, if a and b are the results of previous computations, there is the problem of excess precision. See this article for a discussion in C. The C99 standard solved the problem by making rules explicit for where excess precision could and could not occur, but despite C++ more or less inheriting these rules by deferring to the C standard for the definition of FLT_EVAL_METHOD in cfloat, in practice C compilers take the rules more seriously than C++ compilers. For instance GCC implements the rules for C when compiling with -std=c99, and in this context you can rely on the property to hold, but as of this writing GCC does not implement these rules when used as a C++ compiler.

How to generate NaN, -Infinity and +Infinity in ANSI C?

There is in C99, but not in previous standards AFAIK.

In C99, you'll have NAN and INFINITY macros.

From "Mathematics <math.h>" (§7.12) section

The macro INFINITY expands to a constant expression of type float representing positive or unsigned infinity, if available; ...

If you're stuck with ANSI C89, you're out of luck. See C-FAQ 14.9.

Assigning a variable NaN in python without numpy

Yes -- use math.nan.

>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True

Before Python 3.5, one could use float("nan") (case insensitive).

Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another -- see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.

Instead, use math.isnan(...) if you need to determine if a value is NaN or not.

Furthermore, the exact semantics of the == operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list or dict (or when using custom container types). See Checking for NaN presence in a container for more details.


You can also construct NaN numbers using Python's decimal module:

>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>>
>>> import math
>>> math.isnan(b)
True

math.isnan(...) will also work with Decimal objects.


However, you cannot construct NaN numbers in Python's fractions module:

>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 146, in __new__
numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 130, in __new__
value = Fraction.from_float(numerator)
File "C:\Python35\lib\fractions.py", line 214, in from_float
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.

Incidentally, you can also do float('Inf'), Decimal('Inf'), or math.inf (3.5+) to assign infinite numbers. (And also see math.isinf(...))

However doing Fraction('Inf') or Fraction(float('inf')) isn't permitted and will throw an exception, just like NaN.

If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...) as of Python 3.2+.


If you want to do similar checks with complex numbers, the cmath module contains a similar set of functions and constants as the math module:

  • cmath.isnan(...)
  • cmath.isinf(...)
  • cmath.isfinite(...) (Python 3.2+)
  • cmath.nan (Python 3.6+; equivalent to complex(float('nan'), 0.0))
  • cmath.nanj (Python 3.6+; equivalent to complex(0.0, float('nan')))
  • cmath.inf (Python 3.6+; equivalent to complex(float('inf'), 0.0))
  • cmath.infj (Python 3.6+; equivalent to complex(0.0, float('inf')))

C++ NaN byte representation changes during assignment

0x7fa00000 is a signalling NaN ("sNaN"). 0x7fe00000 is a quiet NaN ("qNaN"). I haven't heard of this behavior under x86, but under ARM sNaNs get converted to the corresponding qNaNs when used in operations, alongside raising an FP exception (which is normally ignored). It looks like the same thing is happening here.

The good news is, they're both NaNs. Unless you're specifically relying on the signalling behavior, everything's going right.



Related Topics



Leave a reply



Submit