Skip to content

Commit

Permalink
Fix convert on Dual (#166)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrhill authored Aug 14, 2024
1 parent 199899d commit 8587e0d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/overloads/conversion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Base.float(::Type{D}) where {P,T,D<:Dual{P,T}} = Dual{float(P),T}

Base.convert(::Type{D}, x::Real) where {P,T,D<:Dual{P,T}} = Dual(x, myempty(T))
Base.convert(::Type{D}, d::D) where {P,T,D<:Dual{P,T}} = d
Base.convert(::Type{N}, d::D) where {N<:Real,P,T,D<:Dual{P,T}} = Dual(convert(T, primal(d)), tracer(d))
Base.convert(::Type{N}, d::D) where {N<:Real,P,T,D<:Dual{P,T}} = Dual(convert(N, primal(d)), tracer(d))

function Base.convert(::Type{Dual{P1,T}}, d::Dual{P2,T}) where {P1,P2,T}
return Dual(convert(P1, primal(d)), tracer(d))
Expand Down
10 changes: 10 additions & 0 deletions test/test_gradient.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ REAL_TYPES = (Float64, Int, Bool, UInt8, Float16, Rational{Int})
@test J(x -> zero(x)^ℯ, 1) [0;;]
@test J(x ->^zero(x), 1) [0;;]

# Conversions
@testset "Conversion to $T" for T in REAL_TYPES
@test J(x -> convert(T, x), 1.0) [1;;]
end

# Round
@test J(round, 1.1) [0;;]
@test J(x -> round(Int, x), 1.1) [0;;]
Expand Down Expand Up @@ -217,6 +222,11 @@ end
@test J(x ->^x, 1) [1;;]
@test J(x -> 0, 1) [0;;]

# Conversions
@testset "Conversion to $T" for T in REAL_TYPES
@test J(x -> convert(T, x), 1.0) [1;;]
end

# Round
@test J(round, 1.1) [0;;]
@test J(x -> round(Int, x), 1.1) [0;;]
Expand Down
14 changes: 14 additions & 0 deletions test/test_hessian.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ H(f, x) = hessian_sparsity(f, x, method)
@test H(x ->^x, 1) [1;;]
@test H(x -> 0, 1) [0;;]

# Conversions
@testset "Conversion to $T" for T in REAL_TYPES
@test H(x -> convert(T, x), 1.0) [0;;]
@test H(x -> convert(T, x^2), 1.0) [1;;]
@test H(x -> convert(T, x)^2, 1.0) [1;;]
end

# Round
@test H(round, 1.1) [0;;]
@test H(x -> round(Int, x), 1.1) [0;;]
Expand Down Expand Up @@ -337,6 +344,13 @@ end
@test H(x ->^x, 1) [1;;]
@test H(x -> 0, 1) [0;;]

# Conversions
@testset "Conversion to $T" for T in REAL_TYPES
@test H(x -> convert(T, x), 1.0) [0;;]
@test H(x -> convert(T, x^2), 1.0) [1;;]
@test H(x -> convert(T, x)^2, 1.0) [1;;]
end

# Round
@test H(round, 1.1) [0;;]
@test H(x -> round(Int, x), 1.1) [0;;]
Expand Down

0 comments on commit 8587e0d

Please sign in to comment.