Python math.isnan() Method



The Python math.isnan() method is used to determine whether a given number NaN (Not a Number). It returns "True" if the number is NaN, and "False" otherwise.

Generally, a number "x" is considered NaN if it does not represent a valid real number and cannot be expressed as a finite value or positive or negative infinity. NaN often arises as a result of undefined operations, such as division by zero or taking the square root of a negative number.

Syntax

Following is the basic syntax of the Python math.isnan() method −

math.isnan(x)

Parameters

This method accepts a numeric value as a parameter representing the value to be checked for NaN.

Return Value

The method returns a boolean value (True or False) indicating whether the given value "x" is NaN.

Example 1

In the following example, we check if the floating-point number "10.5" is NaN using the math.isnan() method −

import math
result = math.isnan(10.5)
print("The result is:",result)       

Output

The output obtained is as follows −

The result is: False

Example 2

Here, we check if positive infinity is NaN using the math.isnan() method −

import math
result = math.isnan(float('inf'))
print("The result is:",result)  

Output

Following is the output of the above code −

The result is: False

Example 3

Now, we use a variable "x" to store NaN. We then check if x is NaN using the math.isnan() method −

import math
x = float('nan')
result = math.isnan(x)
print("The result is:",result)  

Output

We get the output as shown below −

The result is: True

Example 4

In this example, we are checking if the integer number "100" is NaN using the math.isnan() method −

import math
result = math.isnan(100)
print("The result is:",result)  

Output

The result produced is as shown below −

The result is: False
python_maths.htm
Advertisements