Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/dual.jl
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,13 @@ end
function SpecialFunctions.gamma_inc(a::Real, d::Dual{T,<:Real}, ind::Integer) where {T}
x = value(d)
p, q = SpecialFunctions.gamma_inc(a, x, ind)
∂p = exp(-x) * x^(a - 1) / SpecialFunctions.gamma(a) * partials(d)
logx = log(x)
if isfinite(logx)
∂p = exp(-x + (a - 1) * logx - SpecialFunctions.loggamma(a)) * partials(d)
else
# Preserve the power rule at zero for higher-order derivatives.
∂p = exp(-x) * x^(a - 1) / SpecialFunctions.gamma(a) * partials(d)
end
return (Dual{T}(p, ∂p), Dual{T}(q, -∂p))
end

Expand Down
12 changes: 12 additions & 0 deletions test/DualTest.jl
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,18 @@ end
# bug fixes #
#############

@testset "gamma_inc derivatives" begin
for V in (Float32, Float64), (a, x) in ((150, 150), (200, 200), (1, 0), (2, 0)), ind in 0:2
# Compute the reference in arbitrary precision to avoid overflowing intermediates.
expected = V(exp(-big(x)) * big(x)^(a - 1) / factorial(big(a - 1)))
p, q = gamma_inc(V(a), Dual{TestTag}(V(x), one(V)), ind)
@test partials(p, 1) ≈ expected
@test partials(q, 1) ≈ -expected
end
@test ForwardDiff.derivative(x -> ForwardDiff.derivative(y -> gamma_inc(2.0, y, 0)[1], x), 0.0) ≈ 1.0
@test ForwardDiff.derivative(x -> ForwardDiff.derivative(y -> gamma_inc(2.0, y, 0)[2], x), 0.0) ≈ -1.0
end

@testset "Exponentiation of zero" begin
x0 = 0.0
x1 = Dual{:t1}(x0, 1.0)
Expand Down
Loading