The builtin math module defines the attribute nan
which is used to represent a Not-a-Number (NaN) value.
We get a NaN value when we perform an undefined arithmetic operation such as division by 0, or finding the square root of negative numbers.
#import math module
import math
#print the nan value
print(math.nan)
math.nan
The math.nan
value is a floating point value which is equivalent to float("nan")
import math
print(type(math.nan))
print(float("nan"))
The math.isnan()
function returns True
if the argument given has a value of nan.
import math
print(math.isnan(math.nan))
print(math.isnan(float('nan')))
Some things to note
- Two NaN values are never equal to each other.
- Any operation with a NaN value always returns NaN
- There is no negative NaN.
import math
print(math.nan == math.nan)
print(float('nan') == float('nan'))
print(math.nan + 7)
print(-math.nan)