Python math.isnan(x):验证是否为NaN 函数详解

  • Post category:Python

math.isnan(x) 函数用于判断传入的参数 x 是否是一个无效值(NaN)。如果 x 是 NaN,则返回 True,否则返回 False。它可以用于判断浮点数参数是否是 NaN,而不用担心如果该参数是无限大(正无穷大或负无穷大)时会引发异常的问题。

以下是 math.isnan(x) 函数的完整攻略:

语法

math.isnan(x)

参数

  • x:需要判断的数值。

返回值

如果 x 是 NaN,则返回 True,否则返回 False。

示例

示例1

import math

a = float("nan")
b = 5

if math.isnan(a):
    print("a is NaN")
else:
    print("a is not NaN")

if math.isnan(b):
    print("b is NaN")
else:
    print("b is not NaN")

输出结果为:

a is NaN
b is not NaN

示例2

import math
import numpy as np

arr = np.array([1.0, np.nan, 3.0, np.inf, -np.inf])

for x in arr:
    if math.isnan(x):
        print("x is NaN")
    else:
        print("x is not NaN")

输出结果为:

x is not NaN
x is NaN
x is not NaN
x is not NaN
x is not NaN

上面的示例中,第一个示例测试了一个 NaN 值和一个普通数字值。第二个示例中,我们创建了一个包含 NaN、正无穷大、负无穷大等数值的 NumPy 数组,并使用 math.isnan(x) 函数测试了数组中的每个值,输出了相应值的测试结果。

注意,math.isnan(x) 函数只能用于浮点数类型的参数,如果传入其他类型的参数会引发 TypeError 异常。