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-
- 0/0 is undefined and NaN is used for representing it.
- Sqrt(-ve number) cannot be stored as a real number so NaN is used for representing it.
- Log(-ve number) cannot be stored as a real number so NaN is used for representing it.
- Inverse sin or Inverse cos of a number < -1 or number > 1 is also NaN.
- 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.
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.
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.
x is Positive inf x is negative 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