Closed
Description
MWE
using ForwardDiff
f = x -> x .^ 2
x = [1.0, 2.0, 3.0, 4.0]
v = ones(4)
# 1st order (works)
y = ForwardDiff.Dual.(x, v)
fy = f(y)
@assert ForwardDiff.value.(fy) == [1.0, 4.0, 9.0, 16.0]
@assert ForwardDiff.partials.(fy, 1) == [2.0, 4.0, 6.0, 8.0]
# 2nd order (incorrect 2nd derv)
using ForwardDiff: Dual, partials, value
z = Dual.(Dual.(x, v), Dual.(v, v))
fz = f(z)
4-element Vector{Dual{Nothing, Dual{Nothing, Float64, 1}, 1}}:
Dual{Nothing}(Dual{Nothing}(1.0,2.0),Dual{Nothing}(2.0,4.0))
Dual{Nothing}(Dual{Nothing}(4.0,4.0),Dual{Nothing}(4.0,6.0))
Dual{Nothing}(Dual{Nothing}(9.0,6.0),Dual{Nothing}(6.0,8.0))
Dual{Nothing}(Dual{Nothing}(16.0,8.0),Dual{Nothing}(8.0,10.0))
Notice that the 2nd derivative (which should be [2.0, 2.0, 2.0, 2.0]
julia> partials.(partials.(fz, 1), 1)
4-element Vector{Float64}:
4.0
6.0
8.0
10.0
is off exactly by the first derivative.
julia> partials.(partials.(fz, 1), 1) - partials.(value.(fz), 1)
4-element Vector{Float64}:
2.0
2.0
2.0
2.0
I noticed this pattern in another function: f = x -> exp.(x)
:
4-element Vector{Dual{Nothing, Dual{Nothing, Float64, 1}, 1}}:
Dual{Nothing}(Dual{Nothing}(2.718281828459045,2.718281828459045),Dual{Nothing}(2.718281828459045,5.43656365691809))
Dual{Nothing}(Dual{Nothing}(7.38905609893065,7.38905609893065),Dual{Nothing}(7.38905609893065,14.7781121978613))
Dual{Nothing}(Dual{Nothing}(20.085536923187668,20.085536923187668),Dual{Nothing}(20.085536923187668,40.171073846375336))
Dual{Nothing}(Dual{Nothing}(54.598150033144236,54.598150033144236),Dual{Nothing}(54.598150033144236,109.19630006628847))
Metadata
Metadata
Assignees
Labels
No labels