Fact-checked by Grok 2 weeks ago

NaN

NaN, an acronym for "Not a Number", is a special value in the floating-point arithmetic standard used to represent the results of certain arithmetic operations that yield undefined or unrepresentable values, such as dividing zero by zero or taking the of a . This value is neither a valid number nor an , distinguishing it from other special floating-point representations like positive or negative . Introduced as part of the standard, NaN provides a standardized way to handle exceptional conditions in numerical computations across computer systems. The standard, originally published in 1985 and revised in 2008 and 2019, defines in both and floating-point formats, specifying its encoding with an all-ones exponent and a non-zero (significand). There are two categories of NaN: quiet NaNs (qNaNs), which silently propagate through arithmetic operations without signaling an error, and signaling NaNs (sNaNs), which trigger an exception when encountered in computations to alert programmers of potential issues. This distinction allows for flexible error handling, with quiet NaNs commonly used to avoid halting programs on indeterminate results. A notable property of NaN is that it is unequal to every floating-point value, including itself, meaning comparisons like NaN == NaN or NaN < NaN always evaluate to false, which aids in detecting invalid computations. The standard reserves a large number of bit patterns for NaNs—specifically, all those with an all-ones exponent field and a non-zero significand—in common formats like single and double precision, enabling payloads for diagnostic information. NaN's implementation ensures portability of numerical software across compliant hardware and programming languages, such as C, Java, and Python, where functions like isnan() test for its presence.

Overview and Definition

Definition of NaN

In computing, NaN, which stands for "Not a Number," is a special value in floating-point arithmetic used to represent results that are indeterminate or undefined, such as the outcome of dividing zero by zero (0/0) or taking the square root of a negative number like sqrt(-1). This value serves as a marker for numerical anomalies that cannot be expressed as conventional real numbers. Unlike valid floating-point numbers, NaN is distinct in that it is not equal to any real number, including itself, according to the rules of floating-point comparison; for instance, the expression NaN == NaN evaluates to false. It is typically produced as the result of invalid mathematical operations that violate the assumptions of standard arithmetic. The primary purpose of NaN is to enable computations to proceed without immediate termination when encountering errors, thereby facilitating the development of robust numerical software that can handle exceptional conditions gracefully. By propagating through subsequent operations, NaN allows programs to detect and diagnose issues retrospectively rather than crashing. NaN was first introduced in the IEEE 754-1985 standard for binary floating-point arithmetic as a mechanism to manage such exceptional situations in a standardized way.

Historical Development

The concept of representing indeterminate or invalid results in floating-point arithmetic predates the formal definition of NaN, with early computers in the 1960s and 1970s employing ad hoc methods such as special error codes or hardware traps to handle operations like division by zero or square roots of negative numbers. These approaches varied widely across architectures, leading to portability challenges in scientific computing. The standardization of NaN emerged with IEEE 754-1985, which introduced it as a dedicated value to represent undefined or unrepresentable results, such as 0/0 or ∞ - ∞, thereby promoting consistent behavior across diverse hardware platforms. This development was largely driven by William Kahan, who advocated for reliable floating-point arithmetic to mitigate inconsistencies in earlier formats, emphasizing the need for exceptions and special values to support robust numerical software. The standard addressed portability issues by specifying NaN's encoding and propagation rules, marking a pivotal shift toward uniform handling of indeterminate forms in computing. Subsequent revisions refined NaN's capabilities; IEEE 754-2008 introduced optional payloads in NaN representations to carry diagnostic information, such as error codes, while also extending support to decimal floating-point formats with their own NaNs. The 2019 revision further clarified payload handling and canonical forms, enhancing interoperability. Initial adoption faced resistance due to added hardware complexity and performance overhead, but by the 1990s, NaN became widespread in processors like Intel's x87 coprocessors, with full IEEE 754 compliance starting from the 80387 introduced in 1987, and Sun's SPARC architecture (from 1987 onward), which implemented full IEEE 754 compliance. In modern contexts, NaN remains essential for applications like artificial intelligence and machine learning, where it denotes missing or invalid data in numerical arrays, facilitating imputation strategies without disrupting computations. The ISO/IEC 60559 standard, aligning with IEEE 754 since 1989 and updated in subsequent revisions, has extended NaN support internationally, ensuring its role in reliable floating-point operations across global systems.

Floating-Point Representation

Encoding in IEEE 754

In the IEEE 754 standard for binary floating-point arithmetic, NaN values are encoded using a specific bit pattern that distinguishes them from normalized numbers, infinities, and subnormals. The exponent field is set to all ones—the maximum value (0xFF for single precision and 0x7FF for double precision)—while the significand (fraction) field is non-zero, ensuring the representation is invalid for finite or infinite values. The sign bit is arbitrary and can be either 0 or 1, though it is conventionally set to 0 for "positive" NaNs in many implementations. For single-precision (binary32) format, which uses 32 bits (1 sign bit, 8 exponent bits, 23 significand bits), a typical quiet has the hexadecimal representation 0x7FC00000, corresponding to a sign bit of 0, exponent of 0xFF, and significand starting with a 1 in the most significant bit followed by zeros (binary: 0 11111111 10000000000000000000000). In double-precision (binary64) format, using 64 bits (1 sign bit, 11 exponent bits, 52 significand bits), a corresponding quiet is 0x7FF8000000000000 (sign 0, exponent 0x7FF, significand with leading 1 and trailing zeros). These patterns reserve a large number of possible NaN encodings: over 16 million for single precision and approximately 9 quadrillion for double precision. The significand bits beyond the leading bit (used to distinguish quiet and signaling NaNs) form a "payload" that can store diagnostic information, such as error codes or identifiers. In IEEE 754-2008, this payload provides up to 22 bits in single precision and 51 bits in double precision for quiet NaNs, allowing implementations to propagate useful metadata without altering the core NaN semantics. All systems conforming to IEEE 754 must recognize and generate these NaN encodings correctly, though hardware vendors may reserve specific payload patterns for default quiet or signaling NaNs to ensure portability. The distinction between quiet NaNs (which propagate silently) and signaling NaNs (which may raise exceptions) is determined by the most significant bit of the significand, as detailed in subsequent sections.

Quiet and Signaling NaNs

In the IEEE 754 standard for floating-point arithmetic, not-a-number (NaN) values are divided into two distinct categories: quiet NaNs (qNaNs) and signaling NaNs (sNaNs), each serving different roles in error handling and computation. Quiet NaNs are intended to propagate silently through arithmetic operations without raising any exceptions, allowing erroneous results to continue through calculations for later detection. They are commonly used as default outcomes for operations yielding indeterminate values, such as the square root of a negative number, ensuring that computations do not halt unexpectedly. Signaling NaNs, by contrast, are engineered to trigger an invalid operation exception immediately when they participate in any arithmetic operation, thereby notifying the system or programmer of potentially invalid or uninitialized data. This behavior makes sNaNs valuable for debugging purposes, as they act as explicit markers for anomalous conditions that require attention. The binary encoding in IEEE 754 formats distinguishes these types within the significand field (while the exponent is all ones and the significand is non-zero overall): a qNaN has its most significant significand bit set to 1, whereas an sNaN has this bit set to 0, with the remaining significand bits ensuring it is not an infinity. This bit pattern enables hardware and software to differentiate and handle them appropriately during processing. The standard provides usage guidelines to promote consistent behavior: qNaNs are recommended for computed results from invalid operations to facilitate error propagation, while sNaNs should be reserved for programmer-inserted sentinels to flag and trap invalid inputs early. Exception handling for sNaNs is managed by floating-point units (FPUs), which raise the invalid operation flag upon detection in operations; in programming environments like C, this can be queried or managed using the FE_INVALID exception flag from the <fenv.h> header, allowing applications to respond to such signals.

Canonical Forms and Payloads

In the IEEE 754-2008 standard, forms for quiet NaNs (qNaNs) are specified to promote across systems by designating preferred bit patterns as default representations. These forms set the to 0, the exponent to all 1s, the most significant bit of the (the quiet bit) to 1, and all remaining bits to 0, resulting in patterns such as 0x7FC00000 for binary32 and 0x7FF8000000000000 for binary64. This qNaN serves as a fallback when payload information is unavailable or during format conversions, ensuring consistent handling without loss of the quiet NaN distinction from signaling NaNs. NaN payloads utilize the unused bits in the field—after reserving the leading bit for the indicator—to embed additional diagnostic information, such as codes, origins, or application-specific identifiers. In formats, this provides up to 22 bits for binary32 and 51 bits for binary64, while the recommends operations that preserve and propagate these payloads, such as copying the payload from an input qNaN to the output during arithmetic when a single NaN is involved. Payload-aware operations, introduced in IEEE 754-2008, allow explicit reading and writing of this data via functions like getpayload and setpayload, enabling applications to track sources without altering core floating-point behavior. However, payload preservation has limitations: the standard does not mandate full support, and payloads may be lost or default to the in operations like or when combining multiple , where only one input —if representable—is recommended for , though the selection is implementation-defined. For instance, in binary32, the effective size is constrained to 22 bits, limiting the of embedded information, and conversions between formats may truncate or pad payloads unpredictably if not handled explicitly. The IEEE 754-2008 standard extends payload support to decimal floating-point formats, where NaNs include a diagnostic field—up to 7 digits in decimal32, for example—for carrying structured error details, particularly beneficial in financial and decimal-precision applications requiring traceable invalid results. These decimal payloads follow similar propagation rules, with the diagnostic information preserved during operations analogous to binary cases, enhancing reliability in domains sensitive to rounding and exact decimal representation.

Generation and Behavior

Operations Producing NaN

In conforming to the standard, is generated as the result of certain invalid operations that yield indeterminate or undefined values, signaling an invalid operation exception unless masked. These include arithmetic operations where the mathematical outcome cannot be represented deterministically, such as division of zero by zero, which produces a because the expression 0/0 has no defined value. Indeterminate forms like minus also result in , as the operation subtracts two infinite values of potentially differing signs or magnitudes, leading to an difference. Similarly, of zero by yields due to the conflicting limits approached in the 0 × ∞. For example, in resembling C or similar languages:
[float](/page/Float) indeterminate_sub = INFINITY - INFINITY;  // results in qNaN
[float](/page/Float) zero_div_zero = 0.0f / 0.0f;             // results in qNaN
[float](/page/Float) zero_times_inf = 0.0f * INFINITY;        // results in qNaN
The square root of a negative number is another classic case, where √(-x) for x > 0 produces NaN, as the principal square root is undefined for negative arguments in the real numbers. An example in pseudocode:
float neg_sqrt = sqrtf(-1.0f);  // results in qNaN
Mathematical functions often produce NaN when arguments fall outside their defined domains. For instance, the natural logarithm log(x) signals an invalid operation and returns NaN for x ≤ 0, since the logarithm is undefined for non-positive reals. Likewise, operations like the remainder when the divisor is zero (x % 0) generate NaN. In hardware implementations, such as those in modern floating-point units (FPUs), these operations default to producing a quiet (qNaN) to propagate the error silently unless the system is configured to handle signaling NaNs (sNaNs) or raise exceptions explicitly. For example, x87 and SSE FPUs generate qNaN for 0/0 and similar cases, with the invalid operation flag set in the status word if unmasked.

Propagation in Computations

In governed by the standard, exhibits a contagion property whereby any basic arithmetic operation involving a and another floating-point value (finite or infinite) produces a result, ensuring that invalidity spreads through computations. For instance, operations such as , , , and follow this rule: \mathrm{NaN} + 5 = \mathrm{NaN}, \mathrm{NaN} \times \infty = \mathrm{NaN}. This behavior applies similarly to fused multiply-add operations and other compound arithmetic forms. Mathematical functions, including exponential, logarithmic, trigonometric, and square root, propagate NaN by returning a NaN if any input argument is NaN, maintaining the principle of invalid input yielding invalid output. For example, \exp(\mathrm{NaN}) = \mathrm{NaN} and \sqrt{\mathrm{NaN}} = \mathrm{NaN}. This propagation rule extends to most recommended operations in the standard, such as power and hypotenuse functions. An exception to strict NaN propagation occurs in the minNum and maxNum operations, which prioritize numeric results: if one operand is and the other is a valid number, the returns the number rather than NaN. If both operands are , a NaN is returned. These operations were part of IEEE 754-2008 but demoted to recommended status in IEEE 754-2019 due to concerns over associativity. For quiet NaNs, the standard recommends preserving the payload—the diagnostic information in the significand bits—during propagation, such that an operation with a single NaN input produces an output NaN with the same payload. In cases with multiple NaN inputs, the payload from one (often the first or preferred) is typically retained, as in \mathrm{NaN_1} \times \mathrm{NaN_2} yielding a NaN with \mathrm{NaN_1}'s payload. This feature, while not mandatory, aids in error tracing when supported by hardware. NaN propagation in modern floating-point units (FPUs) introduces minimal performance overhead, as dedicated circuitry handles special values efficiently within the execution pipeline without significant additional latency. This design ensures that NaN "infection" occurs seamlessly alongside normal computations.

Comparison Operations Involving NaN

In the floating-point standard, comparison operations involving NaN are defined such that any returns false when at least one is NaN. This includes (==), (!=), less than (<), greater than (>), less than or equal (<=), and greater than or equal (>=). Specifically, NaN is not equal to any value, including itself (NaN != NaN), and NaN is neither less than nor greater than any finite number, , or another NaN. This behavior establishes as an unordered value within the floating-point domain, intentionally violating the trichotomy principle of real numbers (where every pair of numbers is comparable as less, equal, or greater). The design choice ensures predictable propagation of NaN in computations without halting execution, supporting non-stop arithmetic in and software implementations. It also aligns with the equivalence of comparisons like x < y to x - y < 0, since subtracting NaN yields NaN, and any comparison with NaN yields false, maintaining consistency in arithmetic pipelines. A key rationale for these rules is to avoid paradoxes in aggregate functions such as minimum and maximum. For instance, if NaN were considered less than a positive number, min(NaN, 0) might erroneously return NaN instead of 0, propagating invalidity unexpectedly; by returning false for NaN < 0, the function returns the valid operand (0), treating NaN as "absent" in a sensible way. This prevents undefined outcomes in applications like numerical simulations where invalid inputs should not override valid results. To address scenarios requiring a total order, such as sorting algorithms, IEEE 754-2008 introduced the totalOrder predicate, which extends the partial order to include all floating-point values, including NaNs. Under totalOrder, all NaNs are greater than positive infinity. Among NaNs, those with the sign bit set (negative sign) precede those without (positive sign), and within the same sign bit, they are ordered by ascending payload. This allows stable sorting without special NaN handling, as standard relational operators would leave NaNs incomparable, potentially causing algorithm failures. In practice, these rules impact programming and algorithms significantly. For example, a conditional like if (x > 0) evaluates to false for x, which can simplify error detection by excluding invalid values from positive branches without explicit NaN checks. However, sorting arrays containing NaNs requires totalOrder or custom logic to ensure all elements are positioned deterministically, avoiding undefined order in standard implementations.
c
// Example in C: Standard comparisons with NaN
double x = NAN;
double y = 0.0;
printf("%d\n", (x == x));  // 0 (false)
printf("%d\n", (x > y));   // 0 (false)
printf("%d\n", (x < y));   // 0 (false)
This behavior is consistent across compliant systems, ensuring portability in numerical software.

Variants and Extensions

Integer NaN Representations

Unlike floating-point numbers, which benefit from standardized special values like NaN in the IEEE 754 format, integer data types lack a native representation for "Not a Number" or missing values due to their fixed-range, two's complement encoding that utilizes all possible bit patterns for valid integers. Instead, programmers and systems rely on conventions such as sentinel values to indicate invalid or absent data; common choices include -1 for non-negative contexts or INT_MIN (often -2147483648 for 32-bit signed integers) to flag missing entries without overlapping typical data ranges. These sentinels must be carefully selected to avoid ambiguity with legitimate values, and their use requires explicit checks in code to prevent erroneous computations. In programming libraries, integer NaN-like behavior is emulated through flexible data structures. For instance, NumPy does not support NaN in native integer arrays, as inserting np.nan promotes the array to floating-point dtype; however, object dtype arrays can store np.nan alongside integers, allowing mixed-type handling of missing values at the cost of performance and type safety. Pandas addresses this with nullable integer types like Int64, which use a special pd.NA sentinel to represent missing data while preserving integer semantics and avoiding float promotion. In database systems, SQL's NULL serves as a close analog for integers, propagating through operations (e.g., NULL + 3 yields NULL) much like NaN in arithmetic, enabling consistent treatment of unknowns across numeric columns. Some binary data formats and low-level systems reserve specific bit patterns for consistency with floating-point , such as all-1s (0xFFFFFFFF for 32-bit integers), to denote invalid values in serialized integer fields, particularly in scientific data storage where uniform missing indicators aid interoperability. This approach draws inspiration from 's exponent-all-1s encoding but adapts it to integer contexts without hardware support. These representations find primary use in data processing pipelines involving mixed numeric types, such as statistical analysis or machine learning datasets, where uniform missing-value handling simplifies aggregation, filtering, and imputation across integers and floats without repeated type conversions. For example, in pandas DataFrames, nullable integers allow efficient vectorized operations on incomplete datasets, mirroring NaN's role in floating-point computations while mitigating memory overhead from object arrays.

NaN in Non-Floating-Point Contexts

In relational databases adhering to SQL standards, NULL serves as the primary mechanism for representing undefined or missing values, distinct from NaN, which denotes invalid results from floating-point operations. PostgreSQL, for instance, explicitly supports NaN within real and double precision types per IEEE 754, accepting string inputs like 'NaN' (case-insensitive) and treating NaN as greater than all non-NaN values during sorting and indexing to enable efficient tree-based storage. MySQL similarly accommodates NaN in FLOAT and DOUBLE columns, storing it as a valid floating-point bit pattern, though historical bugs have affected its propagation in queries and comparisons. However, systems like SQLite convert NaN inputs to NULL upon insertion, effectively mapping the invalid numerical state to a missing value representation, which can obscure the original intent. In vector graphics and rendering contexts, NaN coordinates signal invalid paths or points, often resulting in skipped elements or rendering artifacts to prevent undefined behavior. The SVG 2 specification acknowledges NaN in coordinate-related computations, such as in the isPointInFill method, where any NaN input yields a false return to indicate invalid geometry. Similarly, in OpenGL shaders, NaN values in vertex attributes or texture coordinates propagate through computations, leading to indeterminate outputs that developers must detect using built-in functions like isnan to avoid visual glitches or crashes in graphics pipelines. Big data frameworks extend NaN handling to support distributed processing of floating-point data, often treating it as a sentinel for invalid but present values rather than outright missing data. Apache Spark distinguishes NaN from NULL in FloatType and DoubleType, defining NaN equality as true (unlike IEEE 754) and grouping all NaNs together in aggregations while sorting them after all other numerics; this customization aids scalability but deviates from strict floating-point norms. In Hadoop ecosystems, such as Hive or Impala on HDFS, NaN is preserved in binary float storage and supported in queries, but comparisons like NaN = NaN evaluate to false, aligning more closely with IEEE semantics during distributed computations. Such inconsistencies in NaN treatment across databases and distributed systems frequently cause bugs, including data loss during migrations (e.g., NaN-to-NULL conversions) or erroneous aggregations in pipelines where NaN propagates unexpectedly. For example, SQLite's retrieval of inserted NaN as 0.0 has led to silent numerical errors in analytics workflows. These issues have prompted proposals for universal sentinels in data interchange standards, such as native NaN support in JSON extensions, to ensure consistent propagation without custom mappings, though adoption remains limited to specific libraries.

Display and Handling

Visual Representation of NaN

In systems compliant with the IEEE 754 floating-point standard, NaN values are recommended to be represented in text output as the string "NaN". This uppercase form is specified in the standard's guidelines for string conversion operations to ensure consistent human-readable identification of invalid numerical results. In programming environments, the exact casing and format can vary slightly by implementation while adhering to the standard. For instance, in C, the printf function with floating-point specifiers like %f or %g typically outputs "nan" or "NaN" for NaN values, with the precise string being implementation-defined but required to round-trip correctly via string-to-float conversion functions like strtod. Similarly, in Python, the str() function applied to a NaN float yields 'nan', while formatting options like '{:g}'.format(float('nan')) may produce 'NaN' in uppercase for certain styles. When examining NaN in low-level debugging or memory dumps, the binary representation is visible in hexadecimal form. For a single-precision quiet NaN under IEEE 754, a common bit pattern is 0x7fc00000, where the exponent field is all ones (0xFF) and the significand is non-zero, distinguishing it from infinities. This hex view highlights the payload bits available for diagnostic information but is not intended for direct user display. In graphical user interfaces, particularly spreadsheets, NaN often appears as an error symbol rather than the literal string to alert users to invalid data. In Microsoft Excel, computations yielding NaN display as #NUM!, while the NA() function produces #N/A for intentionally missing values, which may render as gaps or icons in charts. Some interfaces show blank cells or warning icons to avoid cluttering visualizations. The IEEE 754 standard recommends "NaN" without locale-specific translations to maintain portability, though certain implementations or tools may adapt displays based on user locale, such as using equivalent phrases in non-English environments. Rare errors in non-compliant systems can lead to mistaken displays like "Infinity" for NaN, but standard adherence prevents this.

Programming Language Support

In C and C++, support for NaN adheres to the IEEE 754 floating-point standard, integrated via the <cmath> header, which provides the std::isnan() function to detect whether a floating-point value is NaN. NaN values are typically generated by indeterminate operations, such as dividing zero by zero (0.0 / 0.0), or through explicit construction using functions like std::numeric_limits<double>::quiet_NaN(). The standard distinguishes between quiet NaNs, which propagate silently in computations, and signaling NaNs, which can trigger floating-point exceptions; the latter are accessible via std::numeric_limits<T>::signaling_NaN() and controlled through the (FPU) environment, allowing developers to enable traps for invalid operations. Microsoft implementations further support NaN detection with _isnan() and generation via nan() functions, ensuring compatibility across compilers like and MSVC. Python provides robust NaN handling in its standard library, with the math.isnan() function in the math module returning True for values and adhering to semantics. can be explicitly created using float('nan') or, since Python 3.5, the constant math.nan. For numerical computing, the library extends this support by treating as a special value in , where operations propagate results (e.g., np.array([1.0, np.nan]) + 1 yields [2.0, nan]) and functions like np.isnan() enable element-wise detection; invalid operations often raise RuntimeWarning for debugging. JavaScript implements NaN as a global property of the Number object (Number.NaN), representing undefined or unrepresentable results from operations like 0 / 0. Detection relies on Number.isNaN(), introduced in ECMAScript 2015, which strictly checks if the argument is the primitive NaN value without type coercion, returning false for non-numeric NaNs like NaN.toString(). In contrast, the legacy global isNaN() coerces its input to a number first, potentially misidentifying non-numeric values as NaN. Due to NaN's unique property of inequality to itself, strict equality (===) and loose equality (==) comparisons with NaN always evaluate to false, necessitating dedicated check functions. Support for NaN varies across languages, with notable gaps in older standards; for instance, Fortran versions prior to the 1990 revision (e.g., ) do not natively support representations, requiring workarounds such as compiler flags to enforce IEEE compliance (e.g., -ieee in some implementations) or manual polling of FPU status flags for . Later Fortran standards, starting from Fortran 2003, introduced intrinsic functions like IEEE_IS_NAN for detection, bridging this gap for modern usage. Best practices for handling NaN emphasize using language-specific detection functions—such as std::isnan() in C++, math.isnan() in , or Number.isNaN() in —rather than equality comparisons, as the IEEE 754 rule that NaN is never equal to any value (including itself) can lead to incorrect results like x == x failing for NaN x. This approach ensures reliable propagation and error handling, avoiding subtle bugs in numerical code.

Mathematical Interpretations

NaN in Function Domains

In real analysis, functions are often defined only on restricted subsets of the real numbers, known as their domains. For instance, the natural logarithm function, \ln(x), is defined solely for x > 0, as the logarithm of non-positive values does not yield a real number. When computations encounter inputs outside these domains, such as \ln(0) or \ln(-1), the result is mathematically undefined within the reals. NaN serves as a computational marker for these domain violations, indicating that the operation has produced a value not belonging to the real number system. Within real number theory, NaN aligns with expressions that are undefined or indeterminate, emphasizing its status as a non-element of \mathbb{R}. Consider limits where direct substitution yields an indeterminate form like $0/0; for example, \lim_{x \to 0} \frac{\sin(x)}{x} = 1, yet evaluating \frac{\sin(0)}{0} directly results in the indeterminate $0/0, which computations represent as NaN to signal the need for further analysis rather than a specific real value. This usage underscores NaN's role in flagging scenarios where no unique real number exists, akin to undefined points in limits or function evaluations that cannot be resolved without additional context. In the context of extended real numbers, which augment \mathbb{R} with +\infty and -\infty to handle overflow and divergence, distinguishes itself by representing truly indeterminate forms rather than unbounded growth. While extended reals assign \pm \infty to cases like (e.g., $1/0 = +\infty), indeterminates such as $0 \times \infty or \infty - \infty lack a single value even in this framework and are thus marked by in numerical systems. This contrast ensures that NaN propagates through computations to highlight unresolved ambiguities, separate from the directed infinities used for asymptotic behavior. In , libraries like the GNU Scientific Library (GSL) employ for error propagation in approximations and special function evaluations. For domain errors or singularities—such as arguments leading to undefined results—GSL functions may return alongside an error code like GSL_EDOM, allowing computations to continue while preserving awareness of the invalidity. This approach facilitates robust error tracking in iterative algorithms, where 's propagation helps identify domain issues without immediate program termination.

Relation to Other Special Values

In the IEEE 754 standard, infinities (±∞) represent results from overflow or with a non-zero , such as $1 / 0 = +\infty or -1 / 0 = -\infty, signaling unbounded magnitude without indeterminacy. In contrast, denotes invalid or indeterminate operations, like $0 / 0, \infty / \infty, or $0 \times \infty, where no meaningful numerical value can be assigned. These distinctions ensure that remains algebraically closed, with infinities propagating through most operations (e.g., \infty + 5 = +\infty) unless paired in indeterminate forms that yield . Signed zeros (+0 and -0) provide directionality for limiting behaviors, preserving the sign in arithmetic to distinguish origins, such as $1 / +0 = +\infty versus $1 / -0 = -\infty. However, operations like +0 / +0 or -0 / -0 produce as an invalid result, while basic arithmetic typically maintains the sign (e.g., -1 \times +0 = -0). This interplay allows signed zeros to influence outcomes in functions sensitive to approach direction, but their involvement in invalid computations triggers . The standard establishes a clear exception : invalid operations (e.g., of a negative number) raise the invalid flag and deliver , distinct from (which sets and raises the overflow flag) or (which delivers and raises its dedicated flag). Interactions between these values follow rules where dominates (e.g., \mathrm{NaN} + \infty = \mathrm{NaN}), preventing erroneous finite results and aiding error detection. Such behaviors support robust numerical algorithms by isolating indeterminacies, as seen in eigenvalue computations where special values flag non-convergent or singular cases. The IEEE 754-2019 revision enhances clarity on these relations, refining handling of signed zeros in comparisons and NaN payloads in operations to improve consistency across implementations.

References

  1. [1]
    NaN -- from Wolfram MathWorld
    In the IEEE 754-2008 standard (referred to as IEEE 754 henceforth), NaN (or "not a number") is a symbolic floating-point representation which is neither a ...
  2. [2]
    None
    Nothing is retrieved...<|separator|>
  3. [3]
    Milestones:IEEE Standard 754 for Binary Floating-Point Arithmetic ...
    In 1978, faculty and students at U.C. Berkeley drafted what became IEEE Standard 754 for Binary Floating-Point Arithmetic. Inspired by ongoing collaboration ...
  4. [4]
    [PDF] IEEE Standard for Binary Floating-Point Arithmetic
    NaN. Not a number, a symbolic entity encoded in floating-point format. There are two types of NaNs (6.2). Signaling NaNs signal the invalid operation.
  5. [5]
    NaN payload propagation - unresolved issues
    Apr 11, 2018 · Known and possible uses of NaN payloads​​ Invalid operations such as 0/0, INF-INF, and sqrt(-1) produce a quiet NaN. Most microprocessors set the ...
  6. [6]
    Exceptions arising from IEEE 754 floating-point arithmetic
    For example, the square root of a negative number can produce a NaN, and ... Invalid Operation exception to identify that particular case and ...
  7. [7]
    Floating Point Arithmetic Before IEEE 754 - MathWorks Blogs
    Jan 18, 2019 · This was before personal computers and IEEE 754. It was a real zoo. There were binary and decimal and even a Russian ternary machine. There were ...
  8. [8]
    [PDF] Computer Organization and Design RISC-V Edition
    “Textbook selection is often a frustrating act of compromise— pedagogy, content coverage, quality of exposition, level of rigor, cost.
  9. [9]
    An Interview with the Old Man of Floating-Point - People @EECS
    Robert Stewart to convene meetings in an attempt to reach a consensus under the aegis of the IEEE. Thus was IEEE p754 born. The second meeting was held one ...
  10. [10]
    Milestone-Proposal:IEEE Standard 754 for Floating Point Arithmetic
    May 30, 2023 · William Kahan, who spearheaded the proposal ultimately adopted as IEEE Standard 754. Along with my numerical analysis pursuits, I tracked ...
  11. [11]
    7.4. Imputation of missing values — scikit-learn 1.7.2 documentation
    The following snippet demonstrates how to replace missing values, encoded as np. nan , using the mean feature value of the two nearest neighbors of samples ...Imputing missing values... · SimpleImputer · IterativeImputer · 7.5. Unsupervised...Missing: AI | Show results with:AI<|separator|>
  12. [12]
    [PDF] Annex X IEC 60559 interchange and extended types
    interchange and extended floating-point formats specified in ISO/IEC/IEEE 60559. ... NaN macro is used for initializing an object of the same type that has ...
  13. [13]
    Sample single precision floating-point values for IEEE 754 arithmetic
    0x7FC00000, 0, 0xFF, 100...000, Quiet NaN, f. See Notes on sample single ... See also. Concepts. Single precision data type for IEEE 754 arithmetic · Basic data ...
  14. [14]
    IEEE Arithmetic
    This chapter discusses the arithmetic model specified by the ANSI/IEEE Standard 754-1985 for Binary Floating-Point Arithmetic.
  15. [15]
    Infinity and NaNs
    Nov 27, 2003 · Signalling NaN. signals an invalid operation exception · Quiet NaN. propagates through almost every arithmetic operation without signalling an ...
  16. [16]
    Why are are so many float/double values reserved for NaN?
    Nov 23, 2020 · The NaN is not a singular value. First, at the level of floating-point data (Level 2 in Table 3.1 of IEEE 754-2008), there are two NaNs, a quiet NaN and a ...Not a Number (NaN) - floating point - Stack OverflowHow are NaN and Infinity of a float or double stored in memory?More results from stackoverflow.com
  17. [17]
    On Numbers in CBOR - IETF
    Jul 7, 2025 · A double precision NaN payload contains 51 bits, a single 22 bits and a half 9 bits, in each case all but the first bit of the significand.
  18. [18]
    1. Introduction — Floating Point and IEEE 754 13.0 documentation
    IEEE 754 standardizes how arithmetic results should be approximated in floating point. Whenever working with inexact results, programming decisions can affect ...2. Floating Point · 3. Dot Product: An Accuracy... · 4. Cuda And Floating Point<|control11|><|separator|>
  19. [19]
    [PDF] IEEE Standard for Floating-Point Arithmetic
    Jul 22, 2019 · Abstract: This standard specifies interchange and arithmetic formats and methods for binary and decimal floating-point arithmetic in ...
  20. [20]
    IEEE Floating-Point Representation | Microsoft Learn
    Aug 3, 2021 · Quiet NaNs have a leading one in the significand, and get propagated through an expression. They represent an indeterminate value, such as the ...
  21. [21]
    Quiet NaN -- from Wolfram MathWorld
    A quiet NaN (qNaN) is a NaN that rarely signals a floating-point exception, unlike a signaling NaN (sNaN). qNaNs can provide diagnostic information.
  22. [22]
    IEEE 754 standard implementation choices - Arm Developer
    A most significant fraction bit of zero indicates a Signaling NaN (SNaN). A one indicates a Quiet NaN (QNaN). Two NaN values are treated as different NaNs if ...
  23. [23]
    Optional support for Signaling NaNs - Open Standards
    The existing binary floating-point arithmetic standard IEC-60559 (International version of ANSI IEEE-754) requires two kinds of NaNs: Quiet NaNs and Signaling ...
  24. [24]
    IEEE Standard for Floating-Point Arithmetic revision due in 2019
    Jun 18, 2019 · The new Pi operations complete the set defined in 754-2008. The payload operations allow applications to read and write payloads of NaNs in an ...
  25. [25]
    What every computer scientist should know about floating-point ...
    What every computer scientist should know about floating-point arithmetic. Author: David Goldberg. David Goldberg. Xerox Palo Alto Research Center, Palo Alto ...
  26. [26]
    754-2008 - IEEE Standard for Floating-Point Arithmetic
    Aug 29, 2008 · This standard specifies interchange and arithmetic formats and methods for binary and decimal floating-point arithmetic in computer ...
  27. [27]
    754-2019 - IEEE Standard for Floating-Point Arithmetic
    Jul 22, 2019 · This standard specifies interchange and arithmetic formats and methods for binary and decimal floating-point arithmetic in computer programming environments.
  28. [28]
    The Removal/Demotion of MinNum and MaxNum Operations from ...
    Feb 21, 2017 · 359) It generally uses the term. NaN to denote quiet NaNs. 359) Since NaNs created by IEC 60559 operations are always quiet, quiet NaNs (along ...
  29. [29]
    [PDF] Parallel floating point exception tracking and NaN propagation
    Apr 9, 2025 · The IEEE 754 standard specifies that an operation with a NaN input should generate a NaN output with the same payload. Both of these solutions ...
  30. [30]
    [PDF] The IEEE 754-2008 Floating Point Standard and its Pending Revision
    Five types of operation exceptions. Invalid operation: Operations on a NaN, 0 × ∞, etc. Division by zero: (when the dividend is non-zero). Page 38. IEEE ...
  31. [31]
    Why doesn't Integer represent NaN in Java? - Stack Overflow
    Jul 12, 2013 · Modern computers use 2's complement binary representation for integers, and that representation doesn't have a NaN value. (All values in the ...Can an integer be NaN in C++? - Stack OverflowWhat is NaN (Not a Number) in the words of a beginner?More results from stackoverflow.com
  32. [32]
    Handling Missing Data | Python Data Science Handbook
    A sentinel value reduces the range of valid values that can be represented, and may require extra (often non-optimized) logic in CPU and GPU arithmetic. Common ...
  33. [33]
    Working with missing data — pandas 2.3.3 documentation - PyData |
    pandas uses different sentinel values to represent a missing (also referred to as NA) depending on the data type.Dev · Pandas 2.1.4 documentation · 1.1 · Pandas 1.4.4 documentationMissing: programming | Show results with:programming
  34. [34]
    Numpy integer nan - python - Stack Overflow
    Oct 3, 2012 · A nan is a special value for float arrays only. There are talks about introducing a special bit that would allow non-float arrays to store what in practice ...Converting NaN to Integer - python - Stack OverflowNumPy or Pandas: Keeping array type as integer while having a ...More results from stackoverflow.com
  35. [35]
    Nullable integer data type — pandas 2.3.3 documentation - PyData |
    Because NaN is a float, this forces an array of integers with any missing values to become floating point. In some cases, this may not matter much.
  36. [36]
    NoData specification via IEEE NaN in GeoTIFF for ArcGIS
    Apr 10, 2014 · Since any 32-bit float whose exponent bits are all 1 is considered a NaN, I'm using 0xffffffff (32 1-bits) as my NaN value since it's both a ...
  37. [37]
    8.1. Numeric Types
    ### Summary: PostgreSQL Handling of NaN in Floating-Point Types and Relation to NULL
  38. [38]
  39. [39]
    Re: [sqlite] NaN in, 0.0 out? - Google Groups
    Mar 24, 2012 · SQLite converts NaN inputs into NULL. And sqlite3_column_double() is defined to return 0.0 for any non-numeric value, including NULL.
  40. [40]
    isnan - OpenGL 4 Reference Pages - Khronos Registry
    Description. For each element i of the result, isnan returns true if x [i] is positive or negative floating point NaN (Not a Number) and false otherwise.
  41. [41]
    Data Types - Spark 4.0.1 Documentation
    There is special handling for not-a-number (NaN) when dealing with float or double types that do not exactly match standard floating point semantics.
  42. [42]
    FLOAT data type | Cloudera on Cloud
    For example, the following statement, which evaluates equality between two NaN values, returns false : SELECT CAST('nan' AS FLOAT)=CAST('nan' AS FLOAT);.
  43. [43]
    Database returns nan instead of NULL - Inductive Automation Forum
    Nov 13, 2012 · It seems to only happen when you bring back two columns that are both floats or doubles. NaN is null for floating point values. I will have ...
  44. [44]
    NaN is not handled correctly · Issue #213 · JuliaDatabases/SQLite.jl
    Jun 24, 2020 · A possible solution is to insert/update IEEE-754 special values, +/- Infty and NaNs, as 8-byte blobs. In Sqlite every value can have a different SQL type.
  45. [45]
    Proposal: NaN handling · Issue #68 · michalmuskala/jason - GitHub
    Jan 31, 2019 · Hi all, while the JSON spec doesn't support the handling of NaNs or +-Infinity, quite a few JSON parsers (most notably the default python ...
  46. [46]
  47. [47]
    N2301: NaN Printf Formatting Underspecified - Open Standards
    which style, and the meaning of any n ...
  48. [48]
    IEEE-754 Floating Point Converter - h-schmidt.net
    This page allows you to convert between the decimal representation of a number (like "1.02") and the binary format used by all modern CPUs (aka "IEEE 754 ...
  49. [49]
    NA function - Microsoft Support
    By entering #N/A in cells where you are missing information, you can avoid the problem of unintentionally including empty cells in your calculations.
  50. [50]
    PEP 754 – IEEE 754 Floating Point Special Values | peps.python.org
    Mar 28, 2003 · The output string representation for an IEEE 754 special value also varies by platform. For example, the expression “float(1e3000)”, which is ...
  51. [51]
    std::isnan - cppreference.com
    Aug 8, 2023 · NaN values never compare equal to themselves or to other NaN values. Copying a NaN is not required, by IEEE-754, to preserve its bit ...
  52. [52]
    Infinity and NaN (The GNU C Library)
    IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is ...
  53. [53]
    std::numeric_limits<T>::signaling_NaN - cppreference.com
    Feb 22, 2023 · When a signaling NaN is used as an argument to an arithmetic expression, the appropriate floating-point exception may be raised and the NaN is ...
  54. [54]
    [PDF] Floating-point control in the Intel® C/C++ compiler and libraries or ...
    Mar 21, 2013 · Floating-point control in the Intel® C/C++ compiler and ... Signalling NaN (SNaN). No meaning. 255. (1.)0xxxx… Quiet Nan (QNaN). No ...<|control11|><|separator|>
  55. [55]
    isnan, _isnan, _isnanf - Microsoft Learn
    Oct 26, 2022 · A NaN is generated when the result of a floating-point operation can't be represented in IEEE-754 floating-point format for the specified type.
  56. [56]
    math — Mathematical functions — Python 3.14.0 documentation
    This module provides access to common mathematical functions and constants, including those defined by the C standard.
  57. [57]
    Miscellaneous — NumPy v2.3 Manual
    Special values defined in numpy: nan, inf, NaNs can be used as a poor-man's mask (if you don't care what the original value was) Note: cannot use equality to ...
  58. [58]
    Number.isNaN() - JavaScript - MDN Web Docs - Mozilla
    Jul 10, 2025 · The Number.isNaN() static method determines whether the passed value is the number value NaN, and returns false if the input is not of the Number type.Missing: strict | Show results with:strict
  59. [59]
    isNaN() - JavaScript - MDN Web Docs
    Jul 8, 2025 · The isNaN() function determines whether a value is NaN, first converting the value to a number if necessary.
  60. [60]
    IEEE Floating-Point Arithmetic (Fortran Programming Guide)
    The IEEE standard supports user handling of exceptions, rounding, and precision. Consequently, the standard supports interval arithmetic and diagnosis of ...Missing: history | Show results with:history<|separator|>
  61. [61]
    [PDF] Using GNU Fortran
    This manual documents the use of gfortran, the GNU Fortran compiler. You can find in this manual how to invoke gfortran, as well as its features and ...<|separator|>
  62. [62]
    Algebra - Logarithm Functions - Pauls Online Math Notes
    Nov 16, 2022 · In this section we will introduce logarithm functions. We give the basic properties and graphs of logarithm functions.Missing: analysis | Show results with:analysis
  63. [63]
    Calculus I - L'Hospital's Rule and Indeterminate Forms
    Nov 16, 2022 · L'Hospital's Rule tells us that if we have an indeterminate form 0/0 or ∞/∞ ∞ / ∞ all we need to do is differentiate the numerator and differentiate the ...
  64. [64]
    Affinely Extended Real Numbers -- from Wolfram MathWorld
    The set R union {+infty,-infty} obtained by adjoining two improper elements to the set R of real numbers is normally called the set of (affinely) extended real ...
  65. [65]
    Error Handling — GSL 2.8 documentation - GNU.org
    This chapter describes the way that GSL functions report and handle errors. By examining the status information returned by every function you can determine ...
  66. [66]
    Exceptions and Exception Handling
    IEEE 754 defines five basic types of floating point exceptions: invalid operation, division by zero, overflow, underflow and inexact.Missing: sNaN | Show results with:sNaN
  67. [67]
    IEEE 754 Machine Numbers and Machine Arithmetic - UMD MATH
    In order to make numerical programs portable between different machines, the IEEE 754 standard defines machine numbers and how arithmetic operations should be ...
  68. [68]
    A New IEEE 754 Standard for Floating-Point Arithmetic in an Ever ...
    Jul 6, 2021 · The 2019 version of the IEEE standard provides new capabilities for reliable scientific computing, fixes bugs, and clarifies exceptional cases in operations ...