Python cmath 模块的 cmath.inf 常量定义正无穷大。此常量是一个预定义值,表示大于任何有限数的数字。
我们可以使用 float('inf') 作为整数来表示它为正无穷大。当我们设置一个变量时,它总是大于或小于其他数字。
此常量只能与 Python 中的浮点数一起使用。我们还可以在 Python 数组和其他数据结构(如列表、集合和字典)中使用无穷大值。
语法
以下是 Python cmath.inf 常量的基本语法 -
cmath.inf
返回值
此常量返回浮点无穷大的值。
示例 1
在下面的示例中,我们使用 cmath.inf 函数表示正无穷大和负无穷大。
import cmath
pos_infinity = float('inf')
print(pos_infinity)
neg_infinity = float('-inf')
print(neg_infinity)
输出
获得的结果如下 -
inf
-inf
-inf
示例 2
现在,我们使用 cmath.inf 常量来查找数字列表中的最小值。我们使用正无穷大的 “minimum_value” 变量,然后这些值遍历列表。
import cmath
x = [10, 15, 20, 25, 30, 35]
minimum_value = cmath.inf
for x in x:
if x < minimum_value:
minimum_value = x
print("The minimum value in the list is:", minimum_value)
输出
以下是上述代码的输出 -
The minimum value in the list is: 10
示例 3
在这里,我们使用 cmath.inf 计算算术运算。
import cmath
positive_infinity = -200
print(positive_infinity + 2000)
negative_infinity = 100
print(negative_infinity - 1000)
print(positive_infinity * 1000)
print(1 / negative_infinity)
输出
获得的输出如下 -
1800
-900
-200000
0.01
-900
-200000
0.01
示例 4
在下面的示例中,将有限数除以无限得到零。
import cmath
x = 102
result = x/cmath.inf
print(result)
输出
我们将得到如下输出 -
0.0