|
| 1 | +import math |
| 2 | +from scipy.integrate import quad |
| 3 | +from numpy import inf |
| 4 | + |
| 5 | + |
| 6 | +def gamma(num: float) -> float: |
| 7 | + """ |
| 8 | + https://en.wikipedia.org/wiki/Gamma_function |
| 9 | + In mathematics, the gamma function is one commonly |
| 10 | + used extension of the factorial function to complex numbers. |
| 11 | + The gamma function is defined for all complex numbers except the non-positive integers |
| 12 | +
|
| 13 | +
|
| 14 | + >>> gamma(-1) |
| 15 | + Traceback (most recent call last): |
| 16 | + ... |
| 17 | + ValueError: math domain error |
| 18 | +
|
| 19 | + |
| 20 | +
|
| 21 | + >>> gamma(0) |
| 22 | + Traceback (most recent call last): |
| 23 | + ... |
| 24 | + ValueError: math domain error |
| 25 | +
|
| 26 | +
|
| 27 | + >>> gamma(9) |
| 28 | + 40320.0 |
| 29 | +
|
| 30 | + >>> from math import gamma as math_gamma |
| 31 | + >>> all(gamma(i)/math_gamma(i) <= 1.000000001 and abs(gamma(i)/math_gamma(i)) > .99999999 for i in range(1, 50)) |
| 32 | + True |
| 33 | +
|
| 34 | +
|
| 35 | + >>> from math import gamma as math_gamma |
| 36 | + >>> gamma(-1)/math_gamma(-1) <= 1.000000001 |
| 37 | + Traceback (most recent call last): |
| 38 | + ... |
| 39 | + ValueError: math domain error |
| 40 | +
|
| 41 | +
|
| 42 | + >>> from math import gamma as math_gamma |
| 43 | + >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 |
| 44 | + True |
| 45 | + """ |
| 46 | + |
| 47 | + if num <= 0: |
| 48 | + raise ValueError("math domain error") |
| 49 | + |
| 50 | + return quad(integrand, 0, inf, args=(num))[0] |
| 51 | + |
| 52 | + |
| 53 | +def integrand(x: float, z: float) -> float: |
| 54 | + return math.pow(x, z - 1) * math.exp(-x) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + from doctest import testmod |
| 59 | + |
| 60 | + testmod() |
0 commit comments