當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math gamma()用法及代碼示例


Python用其語言允許進行各種數學運算,這在科學領域具有多種應用。這樣的Python產品之一就是內置的gamma()函數,該函數以數字方式計算函數中傳遞的數字的伽瑪值。

用法:math.gamma(x)
參數:
x: The number whose gamma value needs to be computed.

返回值:伽瑪值,在數值上等於“factorial(x-1)”。


代碼1:演示gamma()的工作

# Python code to demonstrate 
# working of gamma() 
import math 
  
# initializing argument 
gamma_var = 6
  
# Printing the gamma value. 
print ("The gamma value of the given argument is:"
                       + str(math.gamma(gamma_var)))

輸出:

The gamma value of the given argument is:120.0

factorial()和gamma()

伽瑪值也可以使用factorial(x-1),但用例gamma()因為如果我們比較這兩個函數以完成相似的任務,gamma()提供更好的性能。

代碼2:比較中factorial()gamma()

# Python code to demonstrate 
# factorial() vs gamma() 
import math 
import time  
  
# initializing argument 
gamma_var = 6
  
# checking performance  
# gamma() vs factorial() 
start_fact = time.time() 
res_fact = math.factorial(gamma_var-1) 
  
print ("The gamma value using factorial is:" 
                              + str(res_fact)) 
  
print ("The time taken to compute is:"
        + str(time.time() - start_fact)) 
  
print ('\n') 
  
start_gamma = time.time() 
res_gamma = math.gamma(gamma_var) 
  
print ("The gamma value using gamma() is:"
                           + str(res_gamma)) 
  
print ("The time taken to compute is:" 
       + str(time.time() - start_gamma))

輸出:

The gamma value using factorial is:120
The time taken to compute is:9.059906005859375e-06

The gamma value using gamma() is:120.0
The time taken to compute is:5.245208740234375e-06


相關用法


注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python math library | gamma() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。