Skip to content

Commit 36bf73c

Browse files
authored
add Float16 impl
1 parent bb0b5c8 commit 36bf73c

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/gamma.jl

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
# Adapted from Cephes Mathematical Library (MIT license https://en.smath.com/view/CephesMathLibrary/license) by Stephen L. Moshier
2-
gamma(x::Union{Float32, Float64}) = _gamma(x)
3-
4-
function _gamma(x::Float64)
1+
# Float64 version adapted from Cephes Mathematical Library (MIT license https://en.smath.com/view/CephesMathLibrary/license) by Stephen L. Moshier
2+
function gamma(x::Float64)
53
T = Float64
64
if x < 0
75
(isinteger(x) || x==-Inf) && throw(DomainError(x, "NaN result for non-NaN input."))
@@ -49,8 +47,7 @@ function _gamma(x::Float64)
4947
return z * p / q
5048
end
5149

52-
function _gamma(_x::Float32)
53-
isfinite(_x) || return _x
50+
function gamma(_x::Float32)
5451
x = Float64(_x)
5552
if _x < 0
5653
s = sinpi(x)
@@ -74,6 +71,24 @@ function _gamma(_x::Float32)
7471
return Float32(_x<0 ? π / (s * res) : res)
7572
end
7673

74+
function gamma(_x::Float16)
75+
x = Float32(_x)
76+
if _x < 0
77+
s = sinpi(x)
78+
s == 0 && throw(DomainError(_x, "NaN result for non-NaN input."))
79+
x = 1 - x
80+
end
81+
x>13 && return Float16(ifelse(_x>0, Inf32, 0f0))
82+
z = 1f0
83+
while x>1
84+
x -= 1
85+
z *= x
86+
end
87+
num = evalpoly(x, (1.0f0, 0.4170254f0, 0.24081704f0, 0.04071509f0, 0.015839573f0))
88+
den = x*evalpoly(x, (1.0f0, 0.9942411f0, -0.17434932f0, -0.13577922f0, 0.030284522f0))
89+
return Float16(_x<0 ? Float32(π)*den/(s*z*num) : z*num/den)
90+
end
91+
7792
function gamma(n::Integer)
7893
n < 0 && throw(DomainError(n, "`n` must not be negative."))
7994
n == 0 && return Inf*one(n)

0 commit comments

Comments
 (0)