From 8587e0d202826e0cc1823ddfd7fb6190dd0058ad Mon Sep 17 00:00:00 2001 From: Adrian Hill Date: Wed, 14 Aug 2024 18:28:40 +0200 Subject: [PATCH] Fix `convert` on `Dual` (#166) --- src/overloads/conversion.jl | 2 +- test/test_gradient.jl | 10 ++++++++++ test/test_hessian.jl | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/overloads/conversion.jl b/src/overloads/conversion.jl index 56529c35..91f4dd31 100644 --- a/src/overloads/conversion.jl +++ b/src/overloads/conversion.jl @@ -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)) diff --git a/test/test_gradient.jl b/test/test_gradient.jl index 310f7c24..0b4abc32 100644 --- a/test/test_gradient.jl +++ b/test/test_gradient.jl @@ -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;;] @@ -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;;] diff --git a/test/test_hessian.jl b/test/test_hessian.jl index 7fbfda71..24665718 100644 --- a/test/test_hessian.jl +++ b/test/test_hessian.jl @@ -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;;] @@ -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;;]