Python math.nan Constant



The Python math.nan constant represents "Not a Number". It is a predefined value available in Python's math module and is used to denote undefined or unrepresentable numerical values, particularly those that arise from undefined mathematical operations.

In general mathematics, NaN occurs when attempting to perform operations that are mathematically undefined, such as dividing zero by zero, taking the square root of a negative number, or any operation involving infinity.

NaN serves as a placeholder to indicate that the result of a calculation cannot be expressed as a valid numerical value. It is distinct from infinity (∞) and negative infinity (-∞), which represent unbounded values, and is used to handle exceptional cases in numerical calculations.

Syntax

Following is the basic syntax of the Python math.nan constant −

math.nan

Return Value

The constant returns a floating-point nan (Not a Number) value.

Example 1

In the following example, we are creating a NaN value. We initialize a variable "nan_value" with the math.nan constant, which represents "Not a Number" (NaN). The variable "nan_value" holds a value that indicates undefined numerical data −

import math
nan_value = math.nan
print("The value of nan_value is:", nan_value)

Output

The output obtained is as follows −

The value of nan_value is: nan

Example 2

Here, we are filtering out NaN values from a list of data points. We create a new list "valid_data" containing only the non-NaN values from the original list. This technique is commonly used in data processing to handle missing or undefined data points −

import math
data = [2.5, math.nan, 3.7, math.nan, 1.9]
valid_data = [x for x in data if not math.isnan(x)]
print("The valid data points are:", valid_data)

Output

Following is the output of the above code −

The valid data points are: [2.5, 3.7, 1.9]

Example 3

The sum of any number and NaN is always NaN.

In this example, we perform a calculation where one of the operands is NaN −

import math
x = 10
y = math.nan
result = x + y
print("The result of the calculation is:", result)

Output

The result produced is as shown below −

The result of the calculation is: nan

Example 4

Now, we create a list containing numerical values, including NaN values represented by math.nan. We then filter out the NaN values from the list using a list comprehension. The resulting list contains only valid numerical values −

import math
values = [1, math.nan, 3, math.nan, 5]
filtered_values = [x for x in values if not math.isnan(x)]
print("The list after filtering out NaN values is:", filtered_values)

Output

We get the output as shown below −

The list after filtering out NaN values is: [1, 3, 5]
python_maths.htm
Advertisements