ForwardDiff.jacobian Method error

I get a method error with ForwardDiff.jacobian that I fails to understand. Below a MWE.

function fooworks(cvec,xmesh)
    residual = cvec 
    return residual
end 

function foofails(cvec,xmesh)
    residual = zeros(length(cvec)) 
    N = length(cvec)

    for i=1:N 
        residual[i] = cvec[i] 
    end 

    return residual
end 

# generate the mesh  with N elements (intervals) and N+1 nodes
N = 10; h = 1/N; Np1 = N+1; 
xmesh = Vector(0:h:1)

cvec = ones(size(xmesh))
h = cvec->fooworks(cvec,xmesh);
h = cvec->foofails(cvec,xmesh)
ForwardDiff.jacobian(h,cvec)

The error message is:

MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{var"#127#128", Float64}, Float64, 11})
Closest candidates are:
(::Type{T})(::Real, ::RoundingMode) where T<:AbstractFloat at rounding.jl:200
(::Type{T})(::T) where T<:Number at boot.jl:772
(::Type{T})(::AbstractChar) where T<:Union{AbstractChar, Number} at char.jl:50

Help is much appreciated.

residual = zeros(length(cvec)) 

creates an array of Float64 which is not Dual type. create the vector as zeros(eltype(cvec), length(cvec))

1 Like

Hurray! Sincere thx!