Python - AI 助手

Python cmath.inf 常量



Python 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

示例 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

示例 4

在以下示例中,將有限數除以無限數的結果為零。

import cmath
x = 102
result = x/cmath.inf
print(result)

輸出

我們將得到如下輸出 -

0.0
python_modules.htm
廣告