Python cmath 模块的 cmath.isnan() 函数验证值是否为 NaN(Not a Number)。此函数返回布尔值,即如果值为 NaN,则返回 True,否则返回 False。
如果数字 “x” 不代表实数并且不能表示为有限值,即正无穷大或负无穷大,则称其为 NaN。NaN 通常是由未定义的运算引起的,例如取负数的平方根。
语法
以下是 Python cmath.isnan() 函数的基本语法 -
cmath.isnan(x)
参数
此函数接受数值作为参数,并将该值重定向为 NaN。
返回值
此函数返回一个布尔值,该值为 True,给定的数字为 Nan,否则返回 False。
示例 1
在下面的示例中,我们使用 cmath.isnan() 函数验证浮点数 “20.5” 是否为 “NaN” -
import cmath
x = cmath.isnan(20.5)
print(x)
输出
获得的输出如下 -
False
示例 2
在这里,我们使用 cmath.isnan() 函数 - 校正正无穷大是否为 NaN -
import cmath
result = cmath.isnan(float('inf'))
print("The result is:",result)
输出
以下是上述代码的结果 -
The result is: False
示例 3
现在,当我们使用变量 “x” 来存储 NaN 时。然后这个 cmath.isnan() 函数给出正输出。
import cmath
x = float('nan')
y = cmath.isnan(x)
print(y)
输出
我们将得到如下输出 -
True
示例 4
在下面的示例中,如果我们将字符串作为输入传递,则此 cmath.isnan() 函数会给出 TypeError。
import cmath
res = cmath.isnan("Welcome to qikepu")
print(res)
输出
生成的结果如下 -
Traceback (most recent call last):
File "/home/cg/root/86486/main.py", line 2, in
res = cmath.isnan("Welcome to qikepu")
TypeError: must be real number, not str
File "/home/cg/root/86486/main.py", line 2, in
res = cmath.isnan("Welcome to qikepu")
TypeError: must be real number, not str