MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / gamma_recursive

Function gamma_recursive

maths/gamma.py:54–104  ·  view source on GitHub ↗

Calculates the value of Gamma function of num where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...). Implemented using recursion Examples: >>> from math import isclose, gamma as math_gamma >>> gamma_recursive(0.5) 1.7724538509055159 >>> gam

(num: float)

Source from the content-addressed store, hash-verified

52
53
54def gamma_recursive(num: float) -> float:
55 """
56 Calculates the value of Gamma function of num
57 where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...).
58 Implemented using recursion
59 Examples:
60 >>> from math import isclose, gamma as math_gamma
61 >>> gamma_recursive(0.5)
62 1.7724538509055159
63 >>> gamma_recursive(1)
64 1.0
65 >>> gamma_recursive(2)
66 1.0
67 >>> gamma_recursive(3.5)
68 3.3233509704478426
69 >>> gamma_recursive(171.5)
70 9.483367566824795e+307
71 >>> all(isclose(gamma_recursive(num), math_gamma(num))
72 ... for num in (0.5, 2, 3.5, 171.5))
73 True
74 >>> gamma_recursive(0)
75 Traceback (most recent call last):
76 ...
77 ValueError: math domain error
78 >>> gamma_recursive(-1.1)
79 Traceback (most recent call last):
80 ...
81 ValueError: math domain error
82 >>> gamma_recursive(-4)
83 Traceback (most recent call last):
84 ...
85 ValueError: math domain error
86 >>> gamma_recursive(172)
87 Traceback (most recent call last):
88 ...
89 OverflowError: math range error
90 >>> gamma_recursive(1.1)
91 Traceback (most recent call last):
92 ...
93 NotImplementedError: num must be an integer or a half-integer
94 """
95 if num <= 0:
96 raise ValueError("math domain error")
97 if num > 171.5:
98 raise OverflowError("math range error")
99 elif num - int(num) not in (0, 0.5):
100 raise NotImplementedError("num must be an integer or a half-integer")
101 elif num == 0.5:
102 return math.sqrt(math.pi)
103 else:
104 return 1.0 if num == 1 else (num - 1) * gamma_recursive(num - 1)
105
106
107if __name__ == "__main__":

Callers 1

gamma.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected