Python程式計算給定數字的對數伽馬值


在數學中,伽馬函式被認為是任何給定數字階乘的擴充套件。然而,由於階乘僅針對實數定義,伽馬函式超越了在所有複數(負整數除外)上定義階乘的範圍。它由−表示。

Γ(x) = (x-1)!

對數伽馬函式出現是因為伽馬函式僅對較大的數字快速增長,因此對伽馬函式應用對數將大大減慢其增長速度。它也稱為給定數字的自然對數伽馬值

log(Γ(x)) = log((x-1)!)

在Python程式語言中,像其他一些程式語言一樣,對數伽馬函式是使用math.lgamma()函式計算的。但是,在本文中,我們還將研究其他幾種計算數字的對數伽馬值的方法。

輸入輸出場景

讓我們來看一些輸入輸出場景,以使用math.lgamma()方法查詢對數伽馬函式。

假設對數伽馬函式的輸入是一個正整數−

Input: 12
Result: 17.502307845873887

假設對數伽馬函式的輸入是一個負整數−

Input: -12
Result: “ValueError: math domain error”

假設對數伽馬函式的輸入是零−

Input: 0
Result: “ValueError: math domain error”

假設對數伽馬函式的輸入是一個接近零的負十進位制值−

Input: -0.2
Result: 1.761497590833938

使用lgamma()方法時會發生域錯誤,因為該函式針對所有複數(負整數除外)定義。讓我們看看查詢給定數字的對數伽馬值的各種方法。

使用math.lgamma()函式

lgamma()方法在math庫中定義,並返回給定數字的自然對數伽馬值。該方法的語法為−

math.lgamma(x)

其中x是任何複數,負整數除外。

示例

使用math.lgamma()函式查詢對數伽馬值的Python示例如下−

# import math library import math #log gamma of positive integer x1 = 10 print(math.lgamma(x1)) #log gamma of negative complex number x2 = -1.2 print(math.lgamma(x2)) #log gamma of a positive complex number x3 = 3.4 print(math.lgamma(x3))

輸出

上述Python程式碼的輸出如下−

12.801827480081467
1.5791760340399836
1.0923280598027416

使用math.gamma()math.log()函式

在另一種方法中,可以透過首先使用math.gamma()函式查詢數字的伽馬值,然後使用math.log()函式對伽馬值應用對數來找到數字的對數伽馬值。在這裡,我們只是將lgamma()函式分解成多個步驟。

示例

上述過程的Python實現如下−

# import math library import math #log gamma of positive integer x1 = math.gamma(10) print(math.log(x1)) #log gamma of negative complex number x2 = math.gamma(-1.2) print(math.log(x2)) #log gamma of a positive complex number x3 = math.gamma(3.4) print(math.log(x3))

輸出

獲得的輸出為−

12.801827480081469
1.5791760340399839
1.0923280598027414

透過對數字的階乘應用對數

一種更簡單的方法是找到給定數字的階乘,因為伽馬函式被定義為複數的階乘,並使用math.log()方法對計算出的階乘應用對數。

示例

在這個Python示例中,我們使用階乘和math.log()方法來查詢數字的對數伽馬值。使用這種方法的唯一缺點是它僅適用於正整數。

# import math library import math def factorial(n): if n == 1: return 1 else: return n*factorial(n-1) #log gamma of positive integer x1 = 10 y1 = factorial(x1-1) print(math.log(y1)) x2 = 3 y2 = factorial(x2-1) print(math.log(y2)) #log gamma of a positive complex number x3 = 3.4 y3 = factorial(x3-1) print(math.log(y3))

輸出

獲得的輸出為−

12.801827480081469
0.6931471805599453
RecursionError: maximum recursion depth exceeded in comparison

更新於:2022年10月14日

697 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.