Skip to content

Error trying to differentiate through a Complex #239

Open
@dpsanders

Description

@dpsanders

I need to treat a complex function f: C → C as a function from R^2 to R^2. I am doing this as follows:

julia 0.6> function realify(f)

               function g(x)
                   z = Complex(x[1], x[2])
                   z2 = f(z)
                   SVector(reim(z2))
               end

               return g

           end
realify (generic function with 1 method)

julia 0.6> using StaticArrays

julia 0.6> f(z) = z^3 - 1
f (generic function with 1 method)

julia 0.6> const g = realify(f)
g (generic function with 1 method)

julia 0.6> g(SVector(1, 2))
2-element SVector{2,Int64}:
 -12
  -2

When I try to differentiate this, I get the following error:

julia 0.6> using ForwardDiff

julia 0.6> ForwardDiff.jacobian(g, SVector(1, 2))
ERROR: MethodError: Cannot `convert` an object of type ForwardDiff.Dual{ForwardDiff.Tag{#g#1{#f},0x570e4f4889f9f966},Int64,2} to an object of type Signed
This may have arisen from a call to the constructor Signed(...),
since type constructors fall back to convert methods.
Stacktrace:
 [1] ^(::Complex{ForwardDiff.Dual{ForwardDiff.Tag{#g#1{#f},0x570e4f4889f9f966},Int64,2}}, ::Complex{ForwardDiff.Dual{ForwardDiff.Tag{#g#1{#f},0x570e4f4889f9f966},Int64,2}}) at ./complex.jl:625
 [2] f(::Complex{ForwardDiff.Dual{ForwardDiff.Tag{#g#1{#f},0x570e4f4889f9f966},Int64,2}}) at ./REPL[3]:1
 [3] (::#g#1{#f})(::SVector{2,ForwardDiff.Dual{ForwardDiff.Tag{#g#1{#f},0x570e4f4889f9f966},Int64,2}}) at ./REPL[1]:5
 [4] jacobian(::#g#1{#f}, ::SVector{2,Int64}) at /Users/dpsanders/.julia/v0.6/ForwardDiff/src/jacobian.jl:76

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions