Description

NaN, short for “Not a Number”, is a special constant representing an undefined or unrepresentable numerical result in computing. It is commonly encountered in floating-point arithmetic when operations fail to yield a valid number, such as dividing zero by zero or taking the square root of a negative number (in a non-complex number context).

NaN is part of the IEEE 754 standard for floating-point arithmetic, which is used by nearly all modern computing systems, including programming languages like JavaScript, Python, Java, C, C++, and more.

How NaN Works

Common Causes of NaN

OperationExample CodeResult
Division of zero by zero0.0 / 0.0NaN
Square root of a negative numbermath.sqrt(-1)NaN (in real math)
Parsing invalid numeric stringfloat("abc") or int("12a")NaN or Error
Subtracting infinity from infinityInfinity - InfinityNaN
Logarithm of a negative numbermath.log(-2)NaN

NaN in Different Programming Languages

JavaScript

console.log(0 / 0);           // NaN
console.log(Math.sqrt(-1));   // NaN
console.log(parseInt("abc")); // NaN
console.log(NaN === NaN);     // false (!)

JavaScript includes a built-in isNaN() function:

isNaN("hello"); // true

Python

import math
print(math.sqrt(-1))           # ValueError: math domain error

import numpy as np
x = np.nan
print(np.isnan(x))             # True

Python uses float('nan') to represent NaN:

x = float('nan')
print(x != x)  # True, NaN is not equal to itself

C/C++

#include 
#include 

int main() {
    double x = sqrt(-1.0);
    if (isnan(x)) {
        std::cout << "x is NaN" << std::endl;
    }
}

Properties of NaN

  • Non-Reflexive: NaN != NaN (This is always true. NaN is not equal to itself.)
  • Unordered: Any comparison involving NaN returns false: <, >, <=, >=
  • Propagates: Any operation involving NaN usually results in NaN
x = float('nan')
print(x + 5)     # NaN
print(x * 2)     # NaN

Detecting NaN

Python

math.isnan(x)
np.isnan(x)

JavaScript

Number.isNaN(x)     // More reliable than global isNaN()

Java

Double.isNaN(x)

NaN vs null vs undefined

ConceptRepresentsType
NaNInvalid numberNumber
nullIntentional absence of valueObject (JS)
undefinedVariable declared but not assignedUndefined

Use Cases and Scenarios

  • Handling invalid user input (e.g., form parsing)
  • Processing malformed or missing data in datasets
  • Indicating missing values in data science and machine learning workflows (e.g., NaN in pandas)
  • Representing errors in calculations where exceptions are not desirable

Best Practices

  • Always check for NaN before performing operations or comparisons
  • Use appropriate language-specific functions like isNaN(), np.isnan()
  • Avoid relying on == or != to detect NaN
  • In datasets, handle NaN through imputation, removal, or transformation depending on context

Common Mistakes

  • Expecting NaN == NaN to return true
  • Failing to check for NaN before arithmetic operations, leading to downstream errors
  • Using isNaN() globally in JavaScript, which may coerce values and return misleading results

Real-World Examples

In Data Science

import pandas as pd

df = pd.DataFrame({"age": [25, None, 40]})
print(df.isna())

In JavaScript

let val = Number("text");
if (Number.isNaN(val)) {
  console.warn("Invalid number input!");
}

Summary

NaN (Not a Number) is a foundational concept in floating-point arithmetic that represents invalid or unrepresentable values. Its presence signals that something has gone wrong mathematically. Understanding how to detect, manage, and avoid NaN-related bugs is essential in building stable, predictable, and accurate software, especially in fields like data science, finance, and mathematical computing.

Related Terms

  • Infinity
  • Undefined
  • Null
  • Type Coercion
  • Floating-Point Arithmetic
  • IEEE 754 Standard
  • Data Imputation
  • ValueError
  • Falsy Values
  • Missing Data