Python cmath 模块的 cmath.isfinite() 函数验证数字是否为有限。
如果指定的数字是有限数,则此函数返回 True;否则,它将返回 False。在此函数中,如果浮点为正数或负数,则认为浮点数是有限的。
例如,如果我们有一个浮点数 number (x= 3.14),那么这个函数将返回 True,因为 x 是一个有限数。
语法
以下是 Python cmath.isfinite() 函数的基本语法 -
cmath.isfinite(x)
参数
此函数检查给定的数字是否为有限,此函数还接受数值作为参数。
返回值
此函数返回一个布尔值,即 True 或 False。
示例 1
在以下示例中,我们使用 cmath.isfinite() 函数检查给定复数的布尔值。
import cmath
x = cmath.isfinite(10+3j)
print(x)
输出
以下是上述代码的输出 -
True
示例 2
在这里,我们使用 cmath.isfinite() 函数检查无限是否为有限浮点。
import cmath
x = cmath.isfinite(float('inf'))
print(x)
输出
获得的输出如下 -
False
示例 3
现在,我们使用 cmath.isfinite 函数检查 '0' 是一个有限数。
import cmath
result = cmath.isfinite(0)
print("The result is:", result)
输出
我们将得到以下输出 -
The result is: True
示例 4
在下面的示例中,如果给定值不是数字,则此 cmath.isfinite 函数返回 TypeError。
import cmath
res = cmath.isfinite("Welcome to qikepu")
print(res)
输出
结果如下所示 -
Traceback (most recent call last):
File "/home/cg/root/27484/main.py", line 2, in
res = cmath.isfinite("Welcome to qikepu")
TypeError: must be real number, not str
File "/home/cg/root/27484/main.py", line 2, in
res = cmath.isfinite("Welcome to qikepu")
TypeError: must be real number, not str
示例 5
在此示例中,我们使用 cmath.isfinite() 函数检查 NaN(Not a Number) 是否为有限浮点。
import cmath
res = cmath.isfinite(float('NaN'))
print(res)
输出
我们将得到如下所示的输出 -
False