Python math.inf 常量



Python 的 math.inf 常量表示正無窮大。它是 Python 的 math 模組 中預定義的值,用於表示大於任何有限數字的數字。

在一般的數學中,無窮大 (∞) 用於描述值無限增長的情況,或者數學表示式沒有有限結果的情況。無窮大並非通常意義上的數字;而是一個表示無界或無限增長的概念。

語法

以下是 Python math.inf 常量的基本語法:

math.inf

返回值

該常量返回浮點型正無窮大的值。

示例 1

在下面的示例中,我們將變數 "max_value" 初始化為正無窮大 (math.inf)。這在您希望確保變數持有最大可能值並將其與其他值進行比較的情況下非常有用:

import math
max_value = math.inf
print("The maximum value is:", max_value)

輸出

獲得的輸出如下:

The maximum value is: inf

示例 2

在這裡,我們使用 math.inf 常量來查詢一組數字的最小值。我們用正無窮大 (math.inf) 初始化 "minimum_value" 變數,然後 遍歷列表。如果列表中的數字小於當前的 "minimum_value",則相應地更新 "minimum_value":

import math
numbers = [10, 5, 8, 12, 15, 20]
minimum_value = math.inf
for num in numbers:
   if num < minimum_value:
      minimum_value = num
print("The minimum value in the list is:", minimum_value)

輸出

以下是上述程式碼的輸出:

The minimum value in the list is: 5

示例 3

在這個示例中,我們執行一個 算術運算,其中正無窮大 (math.inf) 加到另一個數字上:

import math
result = math.inf + 100
print("The result of infinity plus 100 is:", result)

輸出

由於將任何有限數字加到正無窮大都會得到正無窮大,因此結果將是正無窮大,如下所示:

The result of infinity plus 100 is: inf

示例 4

在數學中,有限數除以無窮大結果為零。現在,我們進行除以正無窮大的運算:

import math
x = 10
result = x / math.inf
print("The result of dividing", x, "by infinity is:", result)

輸出

我們得到如下所示的輸出:

The result of dividing 10 by infinity is: 0.0
python_maths.htm
廣告