From d03dca7c3b4087a8c3058804bcb05cba4e6626da Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Tue, 1 Mar 2022 07:41:29 +0100 Subject: [PATCH] add div methods for Dual --- src/forwarddiff.jl | 7 +++++++ test/test_forwarddiff.jl | 6 +++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/forwarddiff.jl b/src/forwarddiff.jl index 05e82f09..d1aa714b 100644 --- a/src/forwarddiff.jl +++ b/src/forwarddiff.jl @@ -54,6 +54,13 @@ for PT in (Particles, StaticParticles) Dual{T}($PT(value(d) .- p.particles), ntuple(i->$PT(0p.particles .+ partials(d)[i]) ,length(partials(d)))) end + function Base.:(/)(p::$PT, d::Dual{T}) where {T} + Dual{T}($PT(p.particles ./ value(d)), ntuple(i->$PT(0p.particles ./ partials(d)[i]) ,length(partials(d)))) + end + function Base.:(/)(d::Dual{T}, p::$PT) where {T} + Dual{T}($PT(value(d) ./ p.particles), ntuple(i->$PT(0p.particles .+ partials(d)[i]) ,length(partials(d)))) + end + function Base.promote_rule(::Type{ForwardDiff.Dual{T,V,NP}}, ::Type{$PT{S, N}}) where {T, V, NP, S, N} VS = promote_type(V,S) Dual{T, $PT{VS, N}, NP} diff --git a/test/test_forwarddiff.jl b/test/test_forwarddiff.jl index c71c6dd4..9780d967 100644 --- a/test/test_forwarddiff.jl +++ b/test/test_forwarddiff.jl @@ -8,7 +8,7 @@ const FD = ForwardDiff # In the cost function below, we ensure that $cx+dy > 10 \; ∀ \; c,d ∈ P$ by looking at the worst case function cost(params) x,y = params - -(3x+2y) + 10000sum(params .< 0) + 10000*(pmaximum(c*x+d*y) > 10) + -(3x+2y) + 10000sum(params .< 0) + 10000*(pmaximum(c*x+d*y) > 10) + (x/3)*(3/x) - 1 end params = [1., 2] # Initial guess @@ -55,4 +55,8 @@ const FD = ForwardDiff @test pmean(pmean(r[2])) != ref[2] unsafe_comparisons(false) + + x = paramsp[1] + @test FD.derivative(x -> x/2, x) == 1/2 + @test FD.derivative(x -> 2/x, x) ≈ -2/x^2 end