Python math.gamma() 方法



Python 的math.gamma()方法計算伽馬函式,記作Γ。它是階乘()方法對非整數值的數學擴充套件。伽馬函式定義於所有複數,但非正整數除外。

數學上,伽馬函式定義為:

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

其中,e 是自然對數的底數。伽馬函式具有以下性質:

  • 它定義於所有複數 x,但非正整數 (x ≤ 0) 除外。
  • 對於正整數,Γ(n) = (n-1)!,其中 n! 表示 n 的階乘。
  • 它是一個連續且可微的函式。
  • 它滿足遞推關係 Γ(x + 1) = x.Γ(x),對所有 x > 0 成立。
  • 隨著 x 的增大,它的值迅速增長,並且當 x 從右側趨近於零時,它趨於無窮大。

語法

以下是 Python math.gamma() 方法的基本語法:

math.gamma(x)

引數

此方法接受一個實數或數值表示式作為引數,用於計算伽馬函式的值。

返回值

該方法返回在 x 處計算的伽馬函式的值。

示例 1

在下面的示例中,我們使用math.gamma()方法計算正整數的伽馬函式值:

import math
x = 5
result = math.gamma(x)
print("Gamma method for x =", x, ":", result)

輸出

獲得的輸出如下:

Gamma method for x = 5 : 24.0

示例 2

在這裡,我們使用math.gamma()方法計算正實數的伽馬函式值:

import math
x = 2.5
result = math.gamma(x)
print("Gamma method for x =", x, ":", result)

輸出

以上程式碼的輸出如下:

Gamma method for x = 2.5 : 1.3293403881791372

示例 3

在這個例子中,我們使用math.gamma()方法計算x=3和x+1的伽馬函式值的乘積:

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

輸出

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

Expression result for x = 3 : 12.0

示例 4

現在,我們使用math.gamma()方法計算負數的伽馬函式值:

import math
x = -3.5
result = math.gamma(x)
print("Gamma method for x =", x, ":", result)

輸出

產生的結果如下所示:

Gamma method for x = -3.5 : 0.27008820585226917
python_maths.htm
廣告