NaN: Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>AnomieBOT
Rescuing orphaned refs ("wasm" from rev 1286431659)
 
Added reference to the Zig programming language in NaN display
 
Line 1: Line 1:
{{Short description|Value for unrepresentable data}}
{{Short description|Value for unrepresentable data}}
{{Other uses|Nan (disambiguation)}}
{{Other uses|Nan (disambiguation){{!}}Nan}}


In [[computing]], '''NaN''' ({{IPAc-en|n|æ|n}}), standing for '''Not a Number''', is a particular [[value (computer science)|value]] of a numeric [[data type]] (often a [[floating-point arithmetic|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 [[Infinity|infinities]].
In [[computing]], '''NaN''' ({{IPAc-en|n|æ|n}}), standing for '''Not a Number''', is a particular [[value (computer science)|value]] of a numeric [[data type]] (often a [[floating-point arithmetic|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 [[Infinity|infinities]].
Line 12: Line 12:
== Floating point ==
== Floating point ==
{{Floating-point}}
{{Floating-point}}
In floating-point calculations, NaN is not the same as [[extended real number line|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 (computing)|normal number]] in magnitude, a [[subnormal number]], or [[0 (number)|zero]]).
In all floating-point calculations, NaN is not the same as [[extended real number line|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 (computing)|normal number]] in magnitude, a [[subnormal number]], or [[0 (number)|zero]]).


In the [[IEEE 754]] binary interchange formats, NaNs are encoded with the exponent field filled with ones (like infinity values), and some non-zero number in the trailing 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 trailing 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).
In the [[IEEE 754]] binary interchange formats, NaNs are encoded with the exponent field filled with ones (like infinity values), and some non-zero number in the trailing 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 trailing 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).
Line 65: Line 65:
** Remainder {{math|''x'' % ''y''}} when {{math|''x''}} is an infinity or {{math|''y''}} is zero.
** Remainder {{math|''x'' % ''y''}} when {{math|''x''}} is an infinity or {{math|''y''}} is zero.
** The additions {{math|(+∞) + (−∞)}}, {{math|(−∞) + (+∞)}} and equivalent subtractions {{math|(+∞) − (+∞)}} and {{math|(−∞) − (−∞)}}.
** The additions {{math|(+∞) + (−∞)}}, {{math|(−∞) + (+∞)}} and equivalent subtractions {{math|(+∞) − (+∞)}} and {{math|(−∞) − (−∞)}}.
** The [[nth root]] function <math>\sqrt[n]{x}</math> when <math>n</math> is zero.<!-- "rootn" in IEEE-754-2008-->
** Trigonometric functions on infinities: {{math|sin(±∞)}}, {{math|cos(±∞)}}, {{math|tan(±∞)}}.
** The standard treats [[atan2|two-argument arctangent]] specially: its indeterminate forms {{math|atan2(±0,±0)}} and {{math|atan2(±∞,±∞)}} are not NaN but instead various multiples of {{math|π/4}}.
** The standard has alternative functions for powers:
** The standard has alternative functions for powers:
*** The standard {{code|pow}} function and the integer exponent {{code|pown}} function define {{math|[[zero to the power of zero|0<sup>0</sup>]]}}, {{math|1<sup></sup>}}, and {{math|<sup>0</sup>}} as {{math|1}}.
*** The standard {{code|pow}} function and the integer exponent {{code|pown}} function define {{math|[[zero to the power of zero|0<sup>0</sup>]]}}, {{math|1<sup>(±∞)</sup>}}, and {{math|(±∞)<sup>0</sup>}} as {{math|1}}.
*** The {{code|powr}} function defines all three indeterminate forms as invalid operations and so returns NaN.
*** The {{code|powr}} function defines all three indeterminate forms as invalid operations and so returns NaN.
* Real operations with [[complex number|complex]] results, for example:
* Real operations with [[complex number|complex]] results, for example:
Line 72: Line 75:
** The [[logarithm]] of a negative number.
** The [[logarithm]] of a negative number.
** The [[Inverse trigonometric functions|inverse sine or inverse cosine]] of a number that is less than −1 or greater than 1.
** The [[Inverse trigonometric functions|inverse sine or inverse cosine]] of a number that is less than −1 or greater than 1.
 
** The nth root function <math>\sqrt[n]{x}</math> when <math>x</math> is a negative number and <math>n</math> is an even number.
** For the power operation <math>x^{y}</math> with <math>x</math> being a negative number, the standard <code>pow</code> and <code>powr</code> functions behave differently: <code>powr</code> always returns NaN in this case, while <code>pow</code> will only return NaN if <math>y</math> is not an integer.
{{vpad}}
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.<ref name=idl/>
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.<ref name=idl/>


Line 109: Line 114:
* For decimal interchange formats, whether binary or decimal encoded, a NaN is identified by having the top five bits of the combination field after the sign bit set to ones. The sixth bit of the field is the {{code|is_signaling}} flag. That is, this bit is zero if the NaN is quiet, and non-zero if the NaN is signaling.<ref>{{Harvnb|IEEE 754|2019|loc=§3.5.2}}</ref>
* For decimal interchange formats, whether binary or decimal encoded, a NaN is identified by having the top five bits of the combination field after the sign bit set to ones. The sixth bit of the field is the {{code|is_signaling}} flag. That is, this bit is zero if the NaN is quiet, and non-zero if the NaN is signaling.<ref>{{Harvnb|IEEE 754|2019|loc=§3.5.2}}</ref>


For IEEE&nbsp;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&nbsp;3 and required in Release&nbsp;5.<ref>{{cite web|url=http://cdn2.imgtec.com/documentation/MD00083-2B-MIPS64INT-AFP-05.04.pdf|title=MIPS Architecture For Programmers – Volume I-A: Introduction to the MIPS64 Architecture|date=20 November 2013|publisher=MIPS Technologies, Inc.|page=79|access-date=27 September 2017}}</ref>
For IEEE&nbsp;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&nbsp;3 and required in Release&nbsp;5.<ref>{{cite web|url=http://cdn2.imgtec.com/documentation/MD00083-2B-MIPS64INT-AFP-05.04.pdf|title=MIPS Architecture For Programmers – Volume I-A: Introduction to the MIPS64 Architecture|date=20 November 2013|publisher=MIPS Technologies, Inc.|page=79|access-date=27 September 2017|archive-date=28 September 2017|archive-url=https://web.archive.org/web/20170928005646/http://cdn2.imgtec.com/documentation/MD00083-2B-MIPS64INT-AFP-05.04.pdf|url-status=dead}}</ref>


The state of the remaining bits of the trailing significand field are not defined by the standard. These bits encode a value called the 'payload' of the NaN. For the binary formats, the encoding is unspecified. For the decimal formats, the usual encoding of unsigned integers is used. 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 {{code|is_signaling}} 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.
The state of the remaining bits of the trailing significand field are not defined by the standard. These bits encode a value called the 'payload' of the NaN. For the binary formats, the encoding is unspecified. For the decimal formats, the usual encoding of unsigned integers is used. 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 {{code|is_signaling}} 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.
Line 115: Line 120:
=== Canonical NaN ===
=== Canonical NaN ===
{{Confusing|1=section|reason=IEEE 754 already uses "canonical NaN" with the meaning of "canonical encoding of a NaN" (e.g. "isCanonical(x) is true if and only if x is a finite number, infinity, or NaN that is canonical." page 38, but also for totalOrder page 42), thus a different meaning from what is used here|date=February 2024}}
{{Confusing|1=section|reason=IEEE 754 already uses "canonical NaN" with the meaning of "canonical encoding of a NaN" (e.g. "isCanonical(x) is true if and only if x is a finite number, infinity, or NaN that is canonical." page 38, but also for totalOrder page 42), thus a different meaning from what is used here|date=February 2024}}
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.
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.
* On RISC-V, most floating-point operations only ever generate the canonical NaN, even if a NaN is given as the operand (the payload is not propagated).<ref>{{cite web |last1=Embeddev |first1=Five |title="F" Standard Extension for Single-Precision Floating-Point, Version 2.2 / RISC-V Instruction Set Manual, Volume I: RISC-V User-Level ISA |url=https://five-embeddev.com/riscv-isa-manual/latest/f.html#sec:single-float |website=Five EmbedDev}}</ref>{{efn|IEEE 754-2008 recommends, but does not require, propagation of the NaN payload. Most processors choose to obey this recommendation, but do not by themselves generate a non-zero payload.<ref>{{unbulleted list citebundle|1={{cite web |last1=Fog |first1=Agner |title=NaN payload propagation - unresolved issues |url=https://grouper.ieee.org/groups/msc/ANSI_IEEE-Std-754-2019/background/nan-propagation.pdf |date=2018-04-11}}|2={{cite web |last1=Fog Agner |title=Floating point exception tracking and NAN propagation |url=https://www.agner.org/optimize/nan_propagation.pdf |date=2020-04-27}}}}</ref> The RISC-V behavior is thus non-recommended but compliant.}} ARM can enable a "default NaN" mode for this behavior.<ref>{{cite web |title=NaN handling and the Default NaN (ARM Architecture Reference Manual ARMv7-A and ARMv7-R edition) |url=https://developer.arm.com/documentation/ddi0406/c/Application-Level-Architecture/Application-Level-Programmers--Model/Floating-point-data-types-and-arithmetic/NaN-handling-and-the-Default-NaN |website=Documentation – Arm Developer}}</ref> WebAssembly has the same behavior, though it allows two canonical values.<ref name=wasm>{{cite web |title=What is the motivation for 'NaN' canonicalization? · Issue #1463 · WebAssembly/design |url=https://github.com/WebAssembly/design/issues/1463 |website=GitHub |language=en}} &ndash; see response by Dan Gohman "sunfishcode"</ref>
* On RISC-V, most floating-point operations only ever generate the canonical NaN, even if a NaN is given as the operand (the payload is not propagated).<ref>{{cite web |last1=Embeddev |first1=Five |title="F" Standard Extension for Single-Precision Floating-Point, Version 2.2 / RISC-V Instruction Set Manual, Volume I: RISC-V User-Level ISA |url=https://five-embeddev.com/riscv-isa-manual/latest/f.html#sec:single-float |website=Five EmbedDev}}</ref>{{efn|IEEE 754-2008 recommends, but does not require, propagation of the NaN payload. Most processors choose to obey this recommendation, but do not by themselves generate a non-zero payload.<ref>{{unbulleted list citebundle|1={{cite web |last1=Fog |first1=Agner |title=NaN payload propagation - unresolved issues |url=https://grouper.ieee.org/groups/msc/ANSI_IEEE-Std-754-2019/background/nan-propagation.pdf |date=2018-04-11}}|2={{cite web |last1=Fog Agner |title=Floating point exception tracking and NAN propagation |url=https://www.agner.org/optimize/nan_propagation.pdf |date=2020-04-27}}}}</ref> The RISC-V behavior is thus non-recommended but compliant.}} ARM can enable a "default NaN" mode for this behavior.<ref>{{cite web |title=NaN handling and the Default NaN (ARM Architecture Reference Manual ARMv7-A and ARMv7-R edition) |url=https://developer.arm.com/documentation/ddi0406/c/Application-Level-Architecture/Application-Level-Programmers--Model/Floating-point-data-types-and-arithmetic/NaN-handling-and-the-Default-NaN |website=Documentation – Arm Developer}}</ref> WebAssembly has the same behavior, though it allows two canonical values.<ref name=wasm>{{cite web |title=What is the motivation for 'NaN' canonicalization? · Issue #1463 · WebAssembly/design |url=https://github.com/WebAssembly/design/issues/1463 |website=GitHub |language=en}} &ndash; see response by Dan Gohman "sunfishcode"</ref>
* A number of languages do not distinguish among different NaN values, without requiring their implementations to force a certain NaN value. ECMAScript (JavaScript) code treats all NaN as if they are the same value.<ref name=ecma262>{{cite web |title=ECMAScript® 2026 Language Specification - 6.1.6.1 The Number Type |url=https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-ecmascript-language-types-number-type |website=tc39.es |quote=In some implementations, external code might be able to detect a difference between various NaN values, but such behaviour is implementation-defined; to ECMAScript code, all NaN values are indistinguishable from each other. |language=en}}</ref> Java has the same treatment "for the most part".<ref>{{cite web |title=Chapter 4. Types, Values, and Variables |url=https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3 |website=docs.oracle.com |quote=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.}}</ref>
* A number of languages do not distinguish among different NaN values, without requiring their implementations to force a certain NaN value. ECMAScript (JavaScript) code treats all NaN as if they are the same value.<ref name=ecma262>{{cite web |title=ECMAScript® 2026 Language Specification - 6.1.6.1 The Number Type |url=https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-ecmascript-language-types-number-type |website=tc39.es |quote=In some implementations, external code might be able to detect a difference between various NaN values, but such behaviour is implementation-defined; to ECMAScript code, all NaN values are indistinguishable from each other. |language=en}}</ref> Java has the same treatment "for the most part".<ref>{{cite web |title=Chapter 4. Types, Values, and Variables |url=https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3 |website=docs.oracle.com |quote=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.}}</ref>
Line 131: Line 136:


== Integer NaN ==
== 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&nbsp;754]] standard requires that the invalid-operation [[IEEE 754#Exception handling|exception]] be signaled. For example in [[Java programming language|Java]], such operations throw instances of {{code|java.lang.ArithmeticException}}.<ref>{{cite web|url=http://docs.oracle.com/javase/8/docs/api/java/lang/ArithmeticException.html|title=ArithmeticException (Java Platform SE&nbsp;8)|website=docs.oracle.com}}</ref> In [[C (programming language)|C]], they lead to [[undefined behavior]], but if annex&nbsp;F is supported, the operation yields an "invalid" floating-point exception (as required by the IEEE standard) and an unspecified value.
Most fixed-size [[Integer (computer science)|integer formats]] cannot explicitly indicate invalid data. In such a case, when converting NaN to an integer type, the [[IEEE&nbsp;754]] standard requires that the invalid-operation [[IEEE 754#Exception handling|exception]] be signaled.
 
For example in [[Java (programming language)|Java]], such operations throw instances of {{java|java.lang.ArithmeticException}}.<ref>{{cite web|url=http://docs.oracle.com/javase/8/docs/api/java/lang/ArithmeticException.html|title=ArithmeticException (Java Platform SE&nbsp;8)|website=docs.oracle.com}}</ref>
 
In [[C (programming language)|C]], they lead to [[undefined behavior]], but if annex&nbsp;F is supported, the operation yields an "invalid" floating-point exception (as required by the IEEE standard) and an unspecified value.
 
In the [[R (programming language)|R]] language, the minimal signed value (i.e. 0x80000000) of integers is reserved for <code>NA</code> (Not available).{{Citation needed|date=October 2025|reason=This was documented in the past, but this is no longer the case at least in the current version 4.5.1 (2025-06-13) of both the R language definition and the R internals. An official source should be added or this should be rephrased. See also the Talk page.}} Conversions from NaN (or double NA) to integers then yield a <code>NA</code> integer.


[[Perl]]'s {{code|Math::BigInt}} package uses "NaN" for the result of strings that do not represent valid integers.<ref>{{cite web|title=<code>Math::BigInt</code>|url=http://perldoc.perl.org/Math/BigInt.html#Input|website=perldoc.perl.org|access-date=12 June 2015}}</ref>
[[Perl]]'s {{perl2|Math::BigInt}} package uses "NaN" for the result of strings that do not represent valid integers.<ref>{{cite web|title=<code>Math::BigInt</code>|url=http://perldoc.perl.org/Math/BigInt.html#Input|website=perldoc.perl.org|access-date=12 June 2015}}</ref>
<syntaxhighlight lang="console">
<syntaxhighlight lang="doscon">
> perl -mMath::BigInt -e "print Math::BigInt->new('foo')"
> perl -mMath::BigInt -e "print Math::BigInt->new('foo')"
NaN
NaN
Line 142: Line 153:
Different operating systems and programming languages may have different string representations of NaN.
Different operating systems and programming languages may have different string representations of NaN.


  nan (C, C++, Python)
  nan (C, C++, Python, Zig)
  NaN (ECMAScript, Rust, C#, Julia, Java). <small>Julia may show alternative NaN, depending on precision, NaN32, and NaN16; NaN is for Float64 type.</small>
  NaN (ECMAScript, Rust, C#, Julia, Java). <small>Julia may show alternative NaN, depending on precision, NaN32, and NaN16; NaN is for Float64 type.</small>
  NaN%  
  NaN%  
Line 158: Line 169:


* For the C and C++ languages, the sign bit is always shown by the standard-library functions (e.g. {{code|-nan}}) when present. There is no standard display of the payload nor of the signaling status, but a quiet NaN value of a specific payload may either be constructed by providing the string <code>nan(''char-sequence'')</code> to a number-parsing function (e.g. {{code|strtod}}) or by providing the ''char-sequence'' string to {{code|nan()}} (or {{code|nans()}} for sNaN), both interpreted in an implementation-defined manner.
* For the C and C++ languages, the sign bit is always shown by the standard-library functions (e.g. {{code|-nan}}) when present. There is no standard display of the payload nor of the signaling status, but a quiet NaN value of a specific payload may either be constructed by providing the string <code>nan(''char-sequence'')</code> to a number-parsing function (e.g. {{code|strtod}}) or by providing the ''char-sequence'' string to {{code|nan()}} (or {{code|nans()}} for sNaN), both interpreted in an implementation-defined manner.
** [[GNU C Compiler|GCC]] and [[LLVM]] provides built-in implementations of {{code|nan()}} and {{code|nans()}}. They parse the ''char-sequence'' as an integer for {{code|strtoull}} (or a differently-sized equivalent) with its detection of integer bases.
** [[GNU Compiler Collection|GCC]] and [[LLVM]] provides built-in implementations of {{code|nan()}} and {{code|nans()}}. They parse the ''char-sequence'' as an integer for {{code|strtoull}} (or a differently sized equivalent) with its detection of integer bases.
** The [[GNU C Library]]'s float-parser uses the ''char-sequence'' string in "some unspecified fashion".<ref>{{cite web |url=https://www.gnu.org/software/libc/manual/html_node/Parsing-of-Floats.html |title=Parsing of Floats (The GNU C Library) |website=www.gnu.org |access-date=9 September 2021 |quote=If ''chars…'' are provided, they are used in some unspecified fashion to select a particular representation of NaN (there can be several).}}</ref> In practice, this parsing has been equivalent to GCC/LLVM's for up to 64 bits of payload.<!-- bug 28322: stable but undocumented behavior -->
** The [[glibc]] (GNU C Library) float parser uses the ''char-sequence'' string in "some unspecified fashion".<ref>{{cite web |url=https://sourceware.org/glibc/manual/2.42/html_node/Parsing-of-Floats.html |title=Parsing of Floats (The GNU C Library) |website=sourceware.org |access-date=1 October 2025 |quote=If ''chars…'' are provided, they are used in some unspecified fashion to select a particular representation of NaN (there can be several).}}</ref><!-- Stick to some version of the manual so that this (in particular, the quote) remains correct in the future. --> In practice, this parsing has been equivalent to GCC/LLVM's for up to 64 bits of payload.<!-- bug 28322: stable but undocumented behavior -->
** [[Newlib]] does not implement {{code|nan()}} parsing, but {{code|strtod()}} accepts a hexadecimal format without prefix.
** [[Newlib]] does not implement {{code|nan()}} parsing, but {{code|strtod()}} accepts a hexadecimal format without prefix.
** [[musl]] does not implement any payload parsing.
** [[musl]] does not implement any payload parsing.

Latest revision as of 09:52, 13 November 2025

Template:Short description Script error: No such module "other uses".

In computing, NaN (Template:IPAc-en), 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 Template:Sfrac is typically not defined as a numberTemplate:Efn 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

Template:Floating-point In all 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).

In the IEEE 754 binary interchange formats, NaNs are encoded with the exponent field filled with ones (like infinity values), and some non-zero number in the trailing 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 trailing 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 as Template:Block indent where 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 maxNum and minNum 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.[6] 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, Template:Nobr is not logically equivalent to Template:Nobr: 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.

Comparison between NaN and any floating-point value x
(including NaN and ±∞)
Comparison NaN ≥ x NaN ≤ x NaN > x NaN < x NaN = x NaN ≠ x
Result False False False False False True

From these rules, comparing x with itself, Template:Nobr or Template:Nobr, 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.[7]

Operations generating NaN

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

Template:Vpad 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.[9] 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:

  • Filling uninitialized memory with signaling NaNs would produce the invalid operation exception if the data is used before it is initialized
  • Using an sNaN as a placeholder for a more complicated object, such as:

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.Script error: No such module "Unsubst".

Payload operations

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

Encoding

In IEEE 754 interchange formats, NaNs are identified by specific, pre-defined bit patterns unique to NaNs. The sign bit does not matter. For the binary formats, NaNs are represented with the exponent field filled with ones (like infinity values), and some non-zero number in the trailing 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 trailing significand field determined whether a NaN is signaling or quiet. Two different implementations, with reversed meanings, resulted:

  • most processors (including those of the Intel and AMD's x86 family, the Motorola 68000 family, the AIM PowerPC family, the ARM family, the Sun SPARC family, and optionally new MIPS processors) set the signaling/quiet bit to non-zero if the NaN is quiet, and to zero if the NaN is signaling. Thus, on these processors, the bit represents an is_quiet flag;
  • in NaNs generated by the PA-RISC and old MIPS processors, the signaling/quiet bit is zero if the NaN is quiet, and non-zero if the NaN is signaling. Thus, on these processors, the bit represents an is_signaling flag.

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.[13]

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

  • For binary interchange formats, the most significant bit of the trailing significand field is exclusively used to distinguish between quiet and signaling NaNs.[14] (This requirement has been added in the 2019 revision.) Moreover, it should be an is_quiet flag.[15] That is, this bit is non-zero if the NaN is quiet, and zero if the NaN is signaling.
  • For decimal interchange formats, whether binary or decimal encoded, a NaN is identified by having the top five bits of the combination field after the sign bit set to ones. The sixth bit of the field is the is_signaling flag. That is, this bit is zero if the NaN is quiet, and non-zero if the NaN is signaling.[16]

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.[17]

The state of the remaining bits of the trailing significand field are not defined by the standard. These bits encode a value called the 'payload' of the NaN. For the binary formats, the encoding is unspecified. For the decimal formats, the usual encoding of unsigned integers is used. 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 is_signaling 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

Script error: No such module "Unsubst". 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.

  • On RISC-V, most floating-point operations only ever generate the canonical NaN, even if a NaN is given as the operand (the payload is not propagated).[18]Template:Efn ARM can enable a "default NaN" mode for this behavior.[19] WebAssembly has the same behavior, though it allows two canonical values.[20]
  • A number of languages do not distinguish among different NaN values, without requiring their implementations to force a certain NaN value. ECMAScript (JavaScript) code treats all NaN as if they are the same value.[21] Java has the same treatment "for the most part".[22]

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.[23] (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 hypot(±∞, qNaN) and hypot(qNaN, ±∞) is +∞.

The problem is particularly acute for the exponentiation function pow(x, y) = xy. 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 pow(1, qNaN) should produce a qNaN. However, math libraries have typically returned 1 for pow(1, y) for any real number y, and even when y is an infinity. Similarly, they produce 1 for pow(x, 0) even when x is 0 or an infinity. Template:Citation needed span The 2008 version of the IEEE 754 standard says that pow(1, qNaN) and pow(qNaN, 0) 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 pow(−1, ±∞) = 1 instead of qNaN; the reason of this choice is given in the C rationale:[24] "Generally, C99 eschews a NaN result where a numerical value is useful. ... The result of pow(−2, ∞) 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: pown(x, n), where the exponent must be an integer, and powr(x, y), 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 Template:Java.[25]

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.

In the R language, the minimal signed value (i.e. 0x80000000) of integers is reserved for NA (Not available).Script error: No such module "Unsubst". Conversions from NaN (or double NA) to integers then yield a NA integer.

Perl's Template:Perl2 package uses "NaN" for the result of strings that do not represent valid integers.[26]

> 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, Zig)
NaN (ECMAScript, Rust, C#, Julia, Java). 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:

  • For the C and C++ languages, the sign bit is always shown by the standard-library functions (e.g. -nan) when present. There is no standard display of the payload nor of the signaling status, but a quiet NaN value of a specific payload may either be constructed by providing the string nan(char-sequence) to a number-parsing function (e.g. strtod) or by providing the char-sequence string to nan() (or nans() for sNaN), both interpreted in an implementation-defined manner.
    • GCC and LLVM provides built-in implementations of nan() and nans(). They parse the char-sequence as an integer for strtoull (or a differently sized equivalent) with its detection of integer bases.
    • The glibc (GNU C Library) float parser uses the char-sequence string in "some unspecified fashion".[27] In practice, this parsing has been equivalent to GCC/LLVM's for up to 64 bits of payload.
    • Newlib does not implement nan() parsing, but strtod() accepts a hexadecimal format without prefix.
    • musl does not implement any payload parsing.

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

References

Notes

Template:Notelist

Citations

Template:Reflist

Standards

  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".

External links

Template:Use dmy dates

  1. a b Script error: No such module "citation/CS1".
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. Script error: No such module "citation/CS1".
  5. Script error: No such module "citation/CS1".
  6. Script error: No such module "Footnotes".
  7. Standard for Posit Arithmetic (2022)
  8. Script error: No such module "citation/CS1".
  9. Script error: No such module "citation/CS1".
  10. Script error: No such module "Footnotes".
  11. Script error: No such module "citation/CS1".
  12. Script error: No such module "citation/CS1".
  13. Script error: No such module "citation/CS1".
  14. Script error: No such module "Footnotes".
  15. Script error: No such module "Footnotes".
  16. Script error: No such module "Footnotes".
  17. Script error: No such module "citation/CS1".
  18. Script error: No such module "citation/CS1".
  19. Script error: No such module "citation/CS1".
  20. Script error: No such module "citation/CS1". – see response by Dan Gohman "sunfishcode"
  21. Script error: No such module "citation/CS1".
  22. Script error: No such module "citation/CS1".
  23. Script error: No such module "citation/CS1".
  24. Script error: No such module "citation/CS1".
  25. Script error: No such module "citation/CS1".
  26. Script error: No such module "citation/CS1".
  27. Script error: No such module "citation/CS1".