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()方法时会发生域错误,因为该函数针对所有复数除负“整数”定义。让我们看一下找到给定数字的对数gamma的各种方法。
使用math.lgamma()函数
lgamma()方法是由math库定义的,并返回给定数字的自然对数gamma值。该方法的语法是-
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()函数找到一个数的gamma值,然后再使用math.log()函数对gamma值应用对数运算。在这里,我们只是将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