Skip to content
Related Articles

Related Articles

Improve Article
Check if the value is infinity or NaN in Python
  • Last Updated : 16 Mar, 2021

In this article, we will check whether the given value is NaN or Infinity. This can be done using the math module. Let’s see how to check each value in detail.

Check if the value is NaN

NaN Stands for “Not a Number” and it is a numeric datatype used as a proxy for values that are either mathematically undefined or cannot be represented.  There are various examples of them like-

  1. 0/0 is undefined and NaN is used for representing it.
  2. Sqrt(-ve number) cannot be stored as a real number so NaN is used for representing it.
  3. Log(-ve number) cannot be stored as a real number so NaN is used for representing it.
  4. Inverse sin or Inverse cos of a number < -1 or number > 1 is also NaN.
  5. 0 * inf also leads to NaN.

Since NaN is type in itself It is used to assign variables whose values are not yet calculated.

Method 1: To check for NaN we can use math.isnan() function as NaN cannot be tested using == operator.  


import math
x = math.nan
print(f"x contains {x}")
# checks if variable is equal to NaN
    print("x == nan")
    print("x != nan")

x contains nan
x == nan

Method 2: NaN is not equal to NaN and therefore we can exploit this property to check for NaN. The following code demonstrates it.


import math
def isNan(number):
    # This function compares number to itself. 
    # NaN != NaN and therfore it will return
    # true if the number is Nan 
    return number != number
# Driver Code  
x = math.nan

Check if the Value is Infinite

Method 1: To check for infinite in python the function used is math.isinf() which only checks for infinite. To distinguish between positive and negative infinite we can add more logic that checks if the number is greater than 0 or less than 0. The code shows this in action.


import math
# Function checks if negative or 
# positive infinite.
def check(x):
    if(math.isinf(x) and x > 0):
        print("x is Positive inf")
    elif(math.isinf(x) and x < 0):
        print("x is negative inf")
        print("x is not inf")
# Creating inf using math module.
number = math.inf
number = -math.inf
x is Positive inf
x is negative inf

Method 2: Numpy also exposes two APIs to check for positive and negative infinite. which are np.isneginf() and np.isposinf()


# pip install numpy
import numpy as np
print(np.isneginf([np.inf, 0, -np.inf]))
print(np.isposinf([np.inf, 0, -np.inf]))


[False False  True]
[ True False False]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :