![]() |
VOOZH | about |
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.
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:
Since NaN is a type in itself It is used to assign variables whose values are not yet calculated.
To check for NaN we can use math.isnan() function as NaN cannot be tested using == operator.
x contains nan x == nan
Here, we use Numpy to test if the value is NaN in Python.
Output:
x contains nan x == nan
Here, we use Pandas to test if the value is NaN in Python.
Output:
x contains nan x != nan
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.
x is Positive inf x is negative inf
Numpy also exposes two APIs to check for positive and negative infinite. which are np.isneginf() and np.isposinf().
Output
[False False True] [ True False False]
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.
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
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.
x is Positive inf
Time Complexity: O(1)
Space Complexity: O(1)