Open In App

Check if the value is infinity or NaN in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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 for NaN values in Python

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 a type in itself It is used to assign variables whose values are not yet calculated.

Using math.isnan() to Check for NaN values in Python

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

Python3




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


Output

x contains nan
x == nan

Using np.isnan() to Check for NaN values in Python

Here, we use Numpy to test if the value is NaN in Python.

Python3




import numpy as np
 
x = float("nan")
print(f"x contains {x}")
 
# checks if variable is equal to NaN
if(np.isnan(x)):
    print("x == nan")
else:
    print("x != nan")


Output:

x contains nan
x == nan

Using pd.isna()  to Check for NaN values in Python

Here, we use Pandas to test if the value is NaN in Python.

Python3




import pandas as pd
 
x = float("nan")
x = 6
print(f"x contains {x}")
 
# checks if variable is equal to NaN
if(pd.isna(x)):
    print("x == nan")
else:
    print("x != nan")


Output:

x contains nan
x != nan

Check for Infinite values in Python

Using math.isinf() to Check for Infinite values in Python

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.

Python3




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")
     
    else:
        print("x is not inf")
 
 
# Creating inf using math module.
number = math.inf
check(number)
 
number = -math.inf
check(number)


Output

x is Positive inf
x is negative inf

Using np.isneginf() to Check for Infinite values in Python

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

Python3




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


Output

[False False  True]
[ True False False]

Check for finite values in Python

Using math.isfinite() to Check for finite values in Python

Checking for finite values finds values that are not NaN or infinite. Negating this function combines both the check for NaN and inf values into a single function call.

Python3




import math
 
 
candidates = [1, math.nan, math.inf, 1/3, 123]
for value_to_check in candidates:
    print(f"{value_to_check} is NaN or inf: {not math.isfinite(value_to_check)}")


Output

1 is NaN or inf: False
nan is NaN or inf: True
inf is NaN or inf: True
0.3333333333333333 is NaN or inf: False
123 is NaN or inf: False

Using the decimal module:

Approach:

Import the decimal module.
Create a Decimal object from the value.
Use the Decimal.is_infinite() method to check if the value is infinity.
Use the Decimal.is_nan() method to check if the value is NaN.

Python3




import decimal
 
# Positive infinity
x = decimal.Decimal('Infinity')
 
if x.is_infinite():
    print("x is Positive inf")
     
if x.is_finite() and x < 0:
    print("x is negative inf")


Output

x is Positive inf

Time Complexity: O(1)
Space Complexity: O(1)



Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads