The Python gamma function is one of the special Python Math function which is used to calculate the Gamma value of the given argument. In this section, we discuss how to use gamma function in Python Programming language with example. Before we step into the syntax, let us see the mathematical formula behind the gamma function:
Math.gamma(Number) = (Number – 1)!
It means the gamma function subtract one from the Given number, and then it finds the factorial. For example, Math.gamma(6) = 5!
Syntax of a Python gamma Function
The syntax of the gamma Function in Python Programming Language is
Number: It can be a number or a valid numerical expression.
- If the number argument is positive integer, positive or negative decimals, then gamma function returns the output.
- If the number argument is Negative integer, gamma function return ValueError.
- and if it is not a number, the gamma function returns TypeError.
Python gamma Function Example
The Python gamma function is used to calculate the Gamma value of the given argument. In this example, We are going to find the same for different data types and display the output
# Python gamma Function import math Tup = (1, 2, 8, 4 , 5) # Tuple Declaration Lis = [8, 3, 9, 5 , 7] # List Declaration print('Gamma() Function on Positive Number = %d' %math.gamma(2)) print('Gamma() Function on Positive Number = %d' %math.gamma(6)) print('Gamma() Function on Positive Decimal = %.2f' %math.gamma(4.5)) print('Gamma() Function on Negative Decimal = %.2f' %math.gamma(-2.78)) print('Gamma() Function on Tuple Item = %d' %math.gamma(Tup)) print('Gamma() Function on List Item = %d' %math.gamma(Lis)) print('Gamma() Function on Multiple Number = %d' %math.gamma(10 + 20 - 25)) print('Gamma() Function on String Value = ', math.gamma('3'))
- At the beginning, We declared Python List and Tuple with some random values.
- Within the first two statements, We passed the Positive integers as the gamma Function argument. From the above screenshot, you can observe that gamma Function is returning output.
- Within the next two statements, We passed both the Positive and negative decimals as the gamma Function argument. As we said before, gamma Function is returning the output.
- Next two statements, We used the Python Tuple and List items as the gamma Function argument. If you observe the above screenshot, gamma function is working perfectly on them.
- Next statement, We assigned multiple values as the argument and the gamma Function worked without any issue.
- Next, We tried gamma Function on String value. As we said before, it returns TypeError as output
- Within the Python IDE we passed negative integer as an argument for gamma Function. As you can, it is returning ValueError as output.