Add files via upload

This commit is contained in:
avivfaraj 2021-09-03 19:47:55 -04:00 committed by GitHub
parent c1b15a86ba
commit a56525855c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

83
physics/gamma_function.py Normal file
View File

@ -0,0 +1,83 @@
"""
Gamma function is a very useful tool in physics.
It helps calculating complex integral in a convenient way.
for more info: https://en.wikipedia.org/wiki/Gamma_function
"""
# Importing packages
from math import sqrt, pi
from re import match
from typing import Union
def gamma(num : Union[int, float]) -> Union[int, float]:
"""
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:
>>> Gamma of: 0.5
π
>>> Gamma of: 2
1
>>> Gamma of: 3.5
1.875π
"""
if num == 1:
return 1
elif num == 0.5:
return sqrt(pi)
elif num > 1:
return (num - 1) * gamma(num - 1)
else:
# Error
return -2
def test_gamma() -> None:
"""
>>> test_gamma()
"""
assert sqrt(pi) == gamma(0.5)
assert 1 == gamma(1)
assert 1 == gamma(2)
if __name__ == "__main__":
# Initialize boolean
number = True
# Get input from user
input_ = input("Gamma of: ")
# Ensure valid input
try:
# Ensure input matches half-integer (float) pattern
if match(r'^[0-9]*\.5$', input_):
# Convert string to float
num = float(input_)
# Ensure input matches an integer pattern
elif match(r'^[1-9][0-9]*$', input_):
# Convert string to int
num = int(input_)
# Input is not a valid number
else:
# raise an error
raise ValueError
# Ensure print an error message
except ValueError:
print("Invalid input: Must be an integer or an half-integer!")
number = False
finally:
# Ensure input is a valid number
if number:
# Ensure input is an integer
if (isinstance(gamma(num), int)):
# Print result
print(gamma(num))
# Otherwise print results with √π (gamma of 0.5 is √π)
# Therefore all results will be a number times √π
else:
results = "{result:.4f}".format(result=gamma(num) / sqrt(pi))
results = results.rstrip('0').rstrip('.')
if results == "1":
results = ""
print(results + "\u221A\u03c0")