Python math.lgamma() 方法



Python 的 math.lgamma() 方法用於計算伽馬函式絕對值的自然對數,表示為 ln|Γ(x)|。此方法允許在不導致溢位或精度損失的情況下,對大型引數進行精確的伽馬函式計算。

在數學上,伽馬函式絕對值的自然對數定義為 −

$$\mathrm{\ln|\Gamma(x)|\:=\:\ln|\int_{0}^{∞}\:t^{x-1}e^{-t}dt|}$$

其中,e 是自然對數的底數。

注意:要使用此函式,您需要匯入 math 模組

語法

以下是 Python math.lgamma() 方法的基本語法 −

math.lgamma(x)

引數

此方法接受一個實數或數值表示式作為引數,您需要為其計算伽馬函式絕對值的自然對數。

返回值

該方法返回在 x 處計算的伽馬函式絕對值的自然對數。

示例 1

在以下示例中,我們使用 math.lgamma() 方法計算正整數的伽馬函式絕對值的自然對數 −

import math
x = 5
result = math.lgamma(x)
print("The result obtained for x =", x, ":", result)

輸出

獲得的輸出如下 −

The result obtained for x = 5 : 3.178053830347945

示例 2

在這裡,我們使用 math.lgamma() 方法計算正實數的伽馬函式絕對值的自然對數 −

import math
x = 2.5
result = math.lgamma(x)
print("The result obtained for x =", x, ":", result)

輸出

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

The result obtained for x = 2.5 : 0.2846828704729196

示例 3

在此示例中,我們使用 math.lgamma() 方法評估 x=3 和 x + 1 的伽馬函式絕對值的自然對數之和 −

import math
x = 3
result = math.lgamma(x) + math.lgamma(x+1)
print("Expression result for x =", x, ":", result)

輸出

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

Expression result for x = 3 : 2.4849066497880004

示例 4

現在,我們使用 math.lgamma() 方法計算負數的伽馬函式絕對值的自然對數 −

import math
x = -3.5
result = math.lgamma(x)
print("The result obtained for x =", x, ":", result)

輸出

生成的結果如下所示:

The result obtained for x = -3.5 : -1.3090066849930417
python_maths.htm
廣告