Skip to content

derivative(f!, y, x) doesn't work if y is complex, even if x is real #818

Description

@wsshin

Here is an MWE. For f(x) generating a complex array for x::Real, derivative(f, x) works:

julia> VERSION
v"1.12.6"

julia> using ForwardDiff: derivative

julia> f(x::Real) = [cis(x), cis(x)];

julia> derivative(f, 0.0)
2-element Vector{ComplexF64}:
 -0.0 + 1.0im
 -0.0 + 1.0im

However, derivative for an overwriting f! generates an error, if f! overwrites a complex array:

julia> f!(y::AbstractVector{<:Complex}, x::Real) = (y .= cis(x));

julia> y = Vector{ComplexF64}(undef, 2);  # f!(y, x) produces same result as y .= f(x)

julia> derivative(f!, y, 0.0)
ERROR: MethodError: no method matching ForwardDiff.DerivativeConfig(::typeof(f!), ::Vector{ComplexF64}, ::Float64)
The type `ForwardDiff.DerivativeConfig` exists, but no method is defined for this combination of argument types when trying to construct it.

Closest candidates are:
  ForwardDiff.DerivativeConfig(::F, ::AbstractArray{Y}, ::X) where {F, X<:Real, Y<:Real}
   @ ForwardDiff ~/code/ForwardDiff/src/config.jl:82
  ForwardDiff.DerivativeConfig(::F, ::AbstractArray{Y}, ::X, ::T) where {F, X<:Real, Y<:Real, T}
   @ ForwardDiff ~/code/ForwardDiff/src/config.jl:82

Stacktrace:
 [1] derivative(f!::typeof(f!), y::Vector{ComplexF64}, x::Float64)
   @ ForwardDiff ~/code/ForwardDiff/src/derivative.jl:27
 [2] top-level scope
   @ REPL[6]:1

Is this an intentional limitation of derivative(f!, y, x)? Given that f and f! in the above example perform the same calculation except that the latter is overwriting, it looks strange that derivative(f!, y, x) doesn't work while derivative(f, x) works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions