NaN explained

In computing, NaN, standing for Not a Number, is a particular value of a numeric data type (often a floating-point number) which is undefined as a number, such as the result of 0/0. Systematic use of NaNs was introduced by the IEEE 754 floating-point standard in 1985, along with the representation of other non-finite quantities such as infinities.

In mathematics, the result of 0/0 is typically not defined as a number and may therefore be represented by NaN in computing systems.

The square root of a negative number is not a real number, and is therefore also represented by NaN in compliant computing systems. NaNs may also be used to represent missing values in computations.[1] [2]

Two separate kinds of NaNs are provided, termed quiet NaNs and signaling NaNs. Quiet NaNs are used to propagate errors resulting from invalid operations or values. Signaling NaNs can support advanced features such as mixing numerical and symbolic computation or other extensions to basic floating-point arithmetic.

Floating point

In floating-point calculations, NaN is not the same as infinity, although both are typically handled as special cases in floating-point representations of real numbers as well as in floating-point operations. An invalid operation is also not the same as an arithmetic overflow (which would return an infinity or the largest finite number in magnitude) or an arithmetic underflow (which would return the smallest normal number in magnitude, a subnormal number, or zero).

IEEE 754 NaNs are encoded with the exponent field filled with ones (like infinity values), and some non-zero number in the significand field (to make them distinct from infinity values); this allows the definition of multiple distinct NaN values, depending on which bits are set in the significand field, but also on the value of the leading sign bit (but applications are not required to provide distinct semantics for those distinct NaN values).

For example, an IEEE 754 single precision (32-bit) NaN would be encoded aswhere s is the sign (most often ignored in applications) and the x sequence represents a non-zero number (the value zero encodes infinities). In practice, the most significant bit from x is used to determine the type of NaN: "quiet NaN" or "signaling NaN" (see details in Encoding). The remaining bits encode a payload (most often ignored in applications).

Floating-point operations other than ordered comparisons normally propagate a quiet NaN (qNaN). Most floating-point operations on a signaling NaN (sNaN) signal the invalid-operation exception; the default exception action is then the same as for qNaN operands and they produce a qNaN if producing a floating-point result.

The propagation of quiet NaNs through arithmetic operations allows errors to be detected at the end of a sequence of operations without extensive testing during intermediate stages. For example, if one starts with a NaN and adds 1 five times in a row, each addition results in a NaN, but there is no need to check each calculation because one can just note that the final result is NaN. However, depending on the language and the function, NaNs can silently be removed from a chain of calculations where one calculation in the chain would give a constant result for all other floating-point values. For example, the calculation x0 may produce the result 1, even where x is NaN, so checking only the final result would obscure the fact that a calculation before the x0 resulted in a NaN. In general, then, a later test for a set invalid flag is needed to detect all cases where NaNs are introduced[3] (see Function definition below for further details).

In section 6.2 of the old IEEE 754-2008 standard, there are two anomalous functions (the and functions, which return the maximum and the minimum, respectively, of two operands that are expected to be numbers) that favor numbers — if just one of the operands is a NaN then the value of the other operand is returned. The IEEE 754-2019 revision has replaced these functions as they are not associative (when a signaling NaN appears in an operand).[4] [5]

Comparison with NaN

Comparisons are specified by the IEEE 754 standard to take into account possible NaN operands. When comparing two real numbers, or extended real numbers (as in the IEEE 754 floating-point formats), the first number may be either less than, equal to, or greater than the second number. This gives three possible relations. But when at least one operand of a comparison is NaN, this trichotomy does not apply, and a fourth relation is needed: unordered. In particular, two NaN values compare as unordered, not as equal.

As specified, the predicates associated with the <, ≤, =, ≥, > mathematical symbols (or equivalent notation in programming languages) return false on an unordered relation. So, for instance, is not logically equivalent to : on unordered, i.e. when x or y is NaN, the former returns true while the latter returns false. However, ≠ is defined as the negation of =, thus it returns true on unordered.

NaN ≥ x
NaN ≤ xNaN > xNaN < xNaN = xNaN ≠ x
ResultFalseFalseFalseFalseFalseTrue

From these rules, comparing x with itself, or, can be used to test whether x is NaN or non-NaN.

The comparison predicates are either signaling or non-signaling on quiet NaN operands; the signaling versions signal the invalid-operation exception for such comparisons (i.e., by default, this just sets the corresponding status flag in addition to the behavior of the non-signaling versions). The equality and inequality predicates are non-signaling. The other standard comparison predicates associated with the above mathematical symbols are all signaling if they receive a NaN operand. The standard also provides non-signaling versions of these other predicates. The predicate isNaN(''x'') determines whether a value is a NaN and never signals an exception, even if x is a signaling NaN.

The IEEE floating-point standard requires that NaN ≠ NaN hold. In contrast, the 2022 private standard of posit arithmetic has a similar concept, NaR (Not a Real), where NaR = NaR holds.[6]

Operations generating NaN

There are three kinds of operations that can return NaN:[7]

NaNs may also be explicitly assigned to variables, typically as a representation for missing values. Prior to the IEEE standard, programmers often used a special value (such as −99999999) to represent undefined or missing values, but there was no guarantee that they would be handled consistently or correctly.[1]

NaNs are not necessarily generated in all the above cases. If an operation can produce an exception condition and traps are not masked then the operation will cause a trap instead.[8] If an operand is a quiet NaN, and there is also no signaling NaN operand, then there is no exception condition and the result is a quiet NaN. Explicit assignments will not cause an exception even for signaling NaNs.

Quiet NaN

In general, quiet NaNs, or qNaNs, do not raise any additional exceptions, as they propagate through most operations. But the invalid-operation exception is signaled by some operations that do not return a floating-point value, such as format conversions or certain comparison operations.

Signaling NaN

Signaling NaNs, or sNaNs, are special forms of a NaN that, when consumed by most operations, should raise the invalid operation exception and then, if appropriate, be "quieted" into a qNaN that may then propagate. They were introduced in IEEE 754. There have been several ideas for how these might be used:

When encountered, a trap handler could decode the sNaN and return an index to the computed result. In practice, this approach is faced with many complications. The treatment of the sign bit of NaNs for some simple operations (such as absolute value) is different from that for arithmetic operations. Traps are not required by the standard. There are other approaches to this sort of problem that would be more portable.

Payload operations

IEEE 754-2019 recommends the operations getPayload, setPayload, and setPayloadSignaling be implemented, standardizing the access to payloads to streamline application use.[9] According to the IEEE 754-2019 background document, this recommendation should be interpreted as "required for new implementations, with reservation for backward compatibility".[10]

Encoding

In IEEE 754 interchange formats, NaNs are identified by specific, pre-defined bit patterns unique to NaNs. The sign bit does not matter. Binary format NaNs are represented with the exponential field filled with ones (like infinity values), and some non-zero number in the significand field (to make them distinct from infinity values). The original IEEE 754 standard from 1985 (IEEE 754-1985) only described binary floating-point formats, and did not specify how the signaling/quiet state was to be tagged. In practice, the most significant bit of the significand field determined whether a NaN is signaling or quiet. Two different implementations, with reversed meanings, resulted:

The former choice has been preferred as it allows the implementation to quiet a signaling NaN by just setting the signaling/quiet bit to 1. The reverse is not possible with the latter choice because setting the signaling/quiet bit to 0 could yield an infinity.[11]

The 2008 and 2019 revisions of the IEEE 754 standard make formal requirements and recommendations for the encoding of the signaling/quiet state.

For IEEE 754-2008 conformance, the meaning of the signaling/quiet bit in recent MIPS processors is now configurable via the NAN2008 field of the FCSR register. This support is optional in MIPS Release 3 and required in Release 5.[12]

The state/value of the remaining bits of the significand field are not defined by the standard. This value is called the 'payload' of the NaN. If an operation has a single NaN input and propagates it to the output, the result NaN's payload should be that of the input NaN (this is not always possible for binary formats when the signaling/quiet state is encoded by an flag, as explained above). If there are multiple NaN inputs, the result NaN's payload should be from one of the input NaNs; the standard does not specify which.

Canonical NaN

A number of systems have the concept of a "canonical NaN", where one specific NaN value is chosen to be the only possible qNaN generated by floating-point operations not having a NaN input. The value is usually chosen to be a quiet NaN with an all-zero payload and an arbitrarily-defined sign bit.

Using a limited amount of NaN representations allows the system to use other possible NaN values for non-arithmetic purposes, the most important being "NaN-boxing", i.e. using the payload for arbitrary data.[17] (This concept of "canonical NaN" is not the same as the concept of a "canonical encoding" in IEEE 754.)

Function definition

There are differences of opinion about the proper definition for the result of a numeric function that receives a quiet NaN as input. One view is that the NaN should propagate to the output of the function in all cases to propagate the indication of an error. Another view, and the one taken by the ISO C99 and IEEE 754-2008 standards in general, is that if the function has multiple arguments and the output is uniquely determined by all the non-NaN inputs (including infinity), then that value should be the result. Thus for example the value returned by and is +∞.

The problem is particularly acute for the exponentiation function The expressions 00, ∞0 and 1 are considered indeterminate forms when they occur as limits (just like ∞ × 0), and the question of whether zero to the zero power should be defined as 1 has divided opinion.

If the output is considered as undefined when a parameter is undefined, then should produce a qNaN. However, math libraries have typically returned 1 for for any real number y, and even when y is an infinity. Similarly, they produce 1 for even when x is 0 or an infinity. The 2008 version of the IEEE 754 standard says that and should both return 1 since they return 1 whatever else is used instead of quiet NaN. Moreover, ISO C99, and later IEEE 754-2008, chose to specify instead of qNaN; the reason of this choice is given in the C rationale:[18] "Generally, C99 eschews a NaN result where a numerical value is useful. ... The result of is +∞, because all large positive floating-point values are even integers."

To satisfy those wishing a more strict interpretation of how the power function should act, the 2008 standard defines two additional power functions: where the exponent must be an integer, and which returns a NaN whenever a parameter is a NaN or the exponentiation would give an indeterminate form.

Integer NaN

Most fixed-size integer formats cannot explicitly indicate invalid data. In such a case, when converting NaN to an integer type, the IEEE 754 standard requires that the invalid-operation exception be signaled. For example in Java, such operations throw instances of .[19] In C, they lead to undefined behavior, but if annex F is supported, the operation yields an "invalid" floating-point exception (as required by the IEEE standard) and an unspecified value.

Perl's package uses "NaN" for the result of strings that do not represent valid integers.[20] > perl -mMath::BigInt -e "print Math::BigInt->new('foo')"NaN

Display

Different operating systems and programming languages may have different string representations of NaN.

nan (C, C++, Python) NaN (ECMAScript, Rust, C#, Julia). Julia may show alternative NaN, depending on precision, NaN32, and NaN16; NaN is for Float64 type. NaN% NAN (C, C++, Rust) NaNQ (IBM XL and AIX: Fortran, C++ proposal n2290) NaNS (ditto) qNaN sNaN 1.#SNAN (Excel) 1.#QNAN (Excel) -1.#IND (Excel) +nan.0 (Scheme)

Since, in practice, encoded NaNs have a sign, a quiet/signaling bit and optional 'diagnostic information' (sometimes called a payload), these will occasionally be found in string representations of NaNs, too. Some examples are:

Not all languages admit the existence of multiple NaNs. For example, ECMAScript only uses one NaN value throughout.

References

Standards

External links

Notes and References

  1. Book: Bowman, Kenneth. 2006. An Introduction to Programming with IDL: Interactive Data Language. limited. Academic Press. 26. 978-0-12-088559-6.
  2. Book: Press. William H.. Teukolsky. Saul A.. Vetterling. William T.. Flannery. Brian P.. 2007. Numerical Recipes: The Art of Scientific Computing. limited. Cambridge University Press. 34. 978-0-521-88068-8.
  3. Web site: Lecture Notes on the Status of IEEE Standard 754 for Binary Floating-Point Arithmetic. William Kahan . 1 October 1997.
  4. Web site: The Removal/Demotion of MinNum and MaxNum Operations from IEEE 754-2018. David H.C. Chen. 21 February 2017. 6 May 2019.
  5. Web site: 754R Minutes. 19 May 2017. 25 June 2017.
  6. https://posithub.org/docs/posit_standard-2.pdf Standard for Posit Arithmetic (2022)
  7. Web site: What Every Computer Scientist Should Know About Floating-Point. David Goldberg. 1991.
  8. Web site: Intel 64 and IA-32 Architectures Software Developer's Manual Volume 1: Basic Architecture. April 2008. 118–125, 266–267, 334–335.
  9. Web site: Background discussion for the new Payload functions .
  10. Web site: IEEE Standard for Floating-Point Arithmetic revision due in 2019 .
  11. Web site: Re: (long) sNaNs not what they could be.... IEEE. 15 October 2010. 5 November 2020.
  12. Web site: MIPS Architecture For Programmers – Volume I-A: Introduction to the MIPS64 Architecture. 20 November 2013. MIPS Technologies, Inc.. 79. 27 September 2017.
  13. Web site: Embeddev . Five . "F" Standard Extension for Single-Precision Floating-Point, Version 2.2 / RISC-V Instruction Set Manual, Volume I: RISC-V User-Level ISA . Five EmbedDev.
  14. Web site: NaN handling and the Default NaN (ARM Architecture Reference Manual ARMv7-A and ARMv7-R edition) . Documentation – Arm Developer.
  15. Web site: What is the motivation for 'NaN' canonicalization? · Issue #1463 · WebAssembly/design . GitHub . en.  - see response by Dan Gohman "sunfishcode"
  16. Web site: Chapter 4. Types, Values, and Variables . docs.oracle.com . For the most part, the Java SE platform treats NaN values of a given type as though collapsed into a single canonical value, and hence this specification normally refers to an arbitrary NaN as though to a canonical value..
  17. Book: Nystrom . Robert . Crafting Interpreters . 28 July 2021 . Genever Benning . 978-0-9905829-3-9 . § 30.3 NaN Boxing . English.
  18. Web site: Rationale for International Standard—Programming Languages—C, Revision 5.10 . April 2003 . 180.
  19. Web site: ArithmeticException (Java Platform SE 8). docs.oracle.com.
  20. Web site: Math::BigInt. perldoc.perl.org. 12 June 2015.
  21. Web site: Parsing of Floats (The GNU C Library) . www.gnu.org . 9 September 2021 . If chars… are provided, they are used in some unspecified fashion to select a particular representation of NaN (there can be several)..