1
+ """
2
+ Gamma function is a very useful tool in physics.
3
+ It helps calculating complex integral in a convenient way.
4
+ for more info: https://en.wikipedia.org/wiki/Gamma_function
5
+ """
6
+
7
+ # Importing packages
8
+ from math import sqrt , pi
9
+ from re import match
10
+ from typing import Union
11
+
12
+
13
+ def gamma (num : Union [int , float ]) -> Union [int , float ]:
14
+ """
15
+ Calculates the value of Gamma function of num
16
+ where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...).
17
+ Implemented using recursion
18
+ Examples:
19
+ >>> Gamma of: 0.5
20
+ √π
21
+ >>> Gamma of: 2
22
+ 1
23
+ >>> Gamma of: 3.5
24
+ 1.875√π
25
+ """
26
+ if num == 1 :
27
+ return 1
28
+ elif num == 0.5 :
29
+ return sqrt (pi )
30
+ elif num > 1 :
31
+ return (num - 1 ) * gamma (num - 1 )
32
+ # Error
33
+ return - 2
34
+
35
+
36
+ def test_gamma () -> None :
37
+ """
38
+ >>> test_gamma()
39
+ """
40
+ assert sqrt (pi ) == gamma (0.5 )
41
+ assert 1 == gamma (1 )
42
+ assert 1 == gamma (2 )
43
+
44
+
45
+ if __name__ == "__main__" :
46
+ # Initialize boolean
47
+ number = True
48
+ # Get input from user
49
+ input_ = input ("Gamma of: " )
50
+ # Ensure valid input
51
+ try :
52
+ # Ensure input matches half-integer (float) pattern
53
+ if match (r"^[0-9]*\.5$" , input_ ):
54
+ # Convert string to float
55
+ num = float (input_ )
56
+ # Ensure input matches an integer pattern
57
+ elif match (r"^[1-9][0-9]*$" , input_ ):
58
+ # Convert string to int
59
+ num = int (input_ )
60
+ # Input is not a valid number
61
+ else :
62
+ # raise an error
63
+ raise ValueError
64
+ # Ensure print an error message
65
+ except ValueError :
66
+ print ("Error: Input must be an integer or an half-integer!" )
67
+ number = False
68
+ finally :
69
+ # Ensure input is a valid number
70
+ if number :
71
+ print (f"\u0393 ({ num } ) = " , end = "" )
72
+ # Ensure input is an integer
73
+ if isinstance (gamma (num ), int ):
74
+ # Print result
75
+ print (gamma (num ))
76
+ # Otherwise print results with √π (gamma of 0.5 is √π)
77
+ # Therefore all results will be a number times √π
78
+ else :
79
+ results = f"{ gamma (num ) / sqrt (pi ):.4f} "
80
+ results = results .rstrip ("0" ).rstrip ("." )
81
+ if results == "1" :
82
+ results = ""
83
+ print (results + "\u221A \u03c0 " )
0 commit comments