Python math.gamma() 方法
Python的语言允许各种数学运算,在科学领域有多种应用。 Python的一个这样的产品是内置的gamma()
函数,它以数值方式计算函数中传递的数字的 gamma 值。
Syntax : math.gamma(x)
Parameters :
x : The number whose gamma value needs to be computed.
Returns : The gamma value, which is numerically equal to “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
阶乘()与伽玛()
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