Python math.nan Attribute

Vaibhav Vaibhav Jan 30, 2023
  1. Syntax
  2. Example 1: Use math.nan to Get the Value of nan
  3. Example 2: Use math.nan to Check if a Value Is NaN
Python math.nan Attribute

The Python programming language offers a library, math, that contains implementation for various mathematical operations such as trigonometric functions and logarithmic functions.

In computer science, a NaN or Not a Number is a numeric value that can’t be defined or represented. For example, zero divided by zero is undefined; hence, it is considered a NaN.

This article will discuss the NaN value in the math module.

Syntax

math.nan

Parameters

Since it is a variable, it does not accept any parameters.

Returns

Since it is a variable, it does not return anything like a method. It stores the floating point Not a Number or NaN value.

Its value is equivalent to float("nan"), but the two are not equal.

Example 1: Use math.nan to Get the Value of nan

import math

print(math.nan)

Output:

nan

Example 2: Use math.nan to Check if a Value Is NaN

import math

print(math.nan)
print(float("nan"))
print(math.isnan(math.nan))
print(math.isnan(float("nan")))
print(math.isnan(23))
print(math.isnan(44462.244))
print(math.isnan(False))

Output:

nan
nan
True
True
False
False
False

The Python code above depicts how we can confirm if a number is NaN or not. To check if a value is NaN or not, we can use the math.isnan() method.

This method returns True if the input is a Nan; otherwise, a False. From the output, we can easily infer that math.nan and float("nan") are NaN values, while other inputs, namely, integers, floating-point values, and Boolean values, are not NaN values.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Math