Python - AI 助手

Python cmath.isnan() 函数



Python 的 cmath.isnan() 函数用于检查一个值是否为 NaN(非数字)。此函数返回布尔值,如果值为 NaN,则返回 True,否则返回 False。

如果一个数字“x”不表示一个实数,并且不能表示为一个有限值(即正无穷或负无穷),则称该数字为 NaN。NaN 通常是未定义操作的结果,例如对负数进行平方根运算。

语法

以下是 Python cmath.isnan() 函数的基本语法:

cmath.isnan(x)

参数

此函数接受一个数值作为参数,并将其传递给 NaN 检查。

返回值

此函数返回一个布尔值,如果给定数字为 NaN,则返回 True,否则返回 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 Tutorialspoint")
print(res)

输出

产生的结果如下:

Traceback (most recent call last):
  File "/home/cg/root/86486/main.py", line 2, in 
    res = cmath.isnan("Welcome to Tutorialspoint")
TypeError: must be real number, not str
python_modules.htm
广告

© . All rights reserved.