ForwardDiff cannot assign ForwardDiff.Dual to input array

Hello and welcome to the Julia community!

You need to allow the type of the vector over which you are differentiating to be parametric in order for ForwardDiff to operate correctly. Your issue was that by doing params = copy(init) you are forcing the type of params to be an array of floats. Please see the example below.

function f_new(meta::Array{T}, init) where {T<:Real}
    params = Array{T}(undef, size(init)[1], 1)
    for i=1:5
        params[i] = init[i]
    end
    for i=2:5
        params[i] = meta[1] * params[i-1]
    end
    return sum(params)
end

s = [1.,2.,3.,4.,5.]
ForwardDiff.gradient(x -> f_new(x, s), [2.0])

julia> ForwardDiff.gradient(x -> f_new(x, s), [2.0])
1-element Array{Float64,1}:
 49.0
1 Like