Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement partials/value for complex duals #732

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions src/dual.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Dual{T,V,N}(x::Base.TwicePrecision) where {T,V,N} =

@inline value(x) = x
@inline value(d::Dual) = d.value
@inline value(d::Complex{<:Dual}) = complex(value(real(d)), value(imag(d)))

@inline value(::Type{T}, x) where T = x
@inline value(::Type{T}, d::Dual{T}) where T = value(d)
Expand All @@ -101,6 +102,8 @@ end

@inline partials(x) = Partials{0,typeof(x)}(tuple())
@inline partials(d::Dual) = d.partials
@inline partials(d::Complex{<:Dual}, i) = complex(partials(real(d), i), partials(imag(d), i))
@inline partials(d::Complex{<:Dual}) = Partials(complex.(partials(real(d)).values, partials(imag(d)).values))
@inline partials(x, i...) = zero(x)
@inline Base.@propagate_inbounds partials(d::Dual, i) = d.partials[i]
@inline Base.@propagate_inbounds partials(d::Dual, i, j) = partials(d, i).partials[j]
Expand All @@ -119,6 +122,8 @@ end

@inline npartials(::Dual{T,V,N}) where {T,V,N} = N
@inline npartials(::Type{Dual{T,V,N}}) where {T,V,N} = N
@inline npartials(::Complex{<:Dual{T,V,N}}) where {T,V,N} = N
@inline npartials(::Type{<:Complex{<:Dual{T,V,N}}}) where {T,V,N} = N

@inline order(::Type{V}) where {V} = 0
@inline order(::Type{Dual{T,V,N}}) where {T,V,N} = 1 + order(V)
Expand Down
12 changes: 11 additions & 1 deletion test/DualTest.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ using Test
using Printf
using Random
using ForwardDiff
using ForwardDiff: Partials, Dual, value, partials
using ForwardDiff: Partials, Dual, value, partials, npartials

using NaNMath, SpecialFunctions, LogExpFunctions
using DiffRules
Expand Down Expand Up @@ -673,4 +673,14 @@ end
@test ForwardDiff.derivative(x -> sum(1 .+ x .* (0:0.1:1)), 1) == 5.5
end

@testset "Complex value/partials" begin
x = Dual(1,2,3) + im*Dual(4,5,6)
@test value(x) == 1+im*4
@test partials(x,1) == 2 + 5im
@test partials(x,2) == 3 + 6im
@test partials(x) == [2+5im,3+6im]
@test partials(x) isa Partials
@test npartials(x) == npartials(typeof(x)) == 2
end

end # module
Loading