The math.gamma() method is used to calculate the gamma function of a number.
For positive integers, gamma(num) is equivalent to factorial (num-1)!.
Syntax
import math
math.gamma(num)
Parameter
num(required): It is a numeric value.
Return Value
It returns the gamma value of the number as a float.
If num is an either zero(0) or negative integer , it raises a ValueError.
If num is not a number , it raises TypeError.
Visual Representation
Example 1: How to Use math.gamma() method
import math
print(math.gamma(1))
print(math.gamma(5))
print(math.gamma(0.4))
print(math.gamma(-3.9))
Output
1.0
24.0
2.2181595437576878
0.49190581737781736
Example 2: Passing zero and negative integer
import math
print(math.gamma(0))
print(math.gamma(-5))
Output
ValueError: math domain error
ValueError: math domain error
Example 3: Difference between factorial() and gamma()
The main difference between factorial() and gamma() is that factorial() is only defined for non-negative integers, while gamma() is defined for all complex numbers except negative integers and zero. This makes gamma() more versatile in mathematical and scientific computations.
import math
# Gamma of an integer
print(math.gamma(5))
# Factorial of an integer
print(math.factorial(5))
# Gamma of an non-integer
print(math.gamma(4.5))
# Factorial of an non-integer
print(math.factorial(4.5))
Output
24.0
120
11.631728396567452
ValueError: factorial() only accepts integral values
In the above example, math.gamma(4.5) demonstrates the Gamma function’s ability to handle non-integer inputs, a calculation not possible with math.factorial() which throws a ValueError for non-integer values.