# Symbolic derivation of complex valued functions with Symbolics.jl

when there is im (the imaginery number i) in the function I get zero for the derivative which is obviously wrong. We can replace im with a symbol like I and then differentiate, but I was wondering
maybe there is a better way to do it.

``````using Symbolics
@variables t
D = Differential(t)
z = im*t
D(z)
expand_derivatives(D(z))  #gives 0!
``````
3 Likes

I played a bit with this

``````using Symbolics
@variables x::Float64
D = Differential(x)
@show D
@show D(x)
@show expand_derivatives(D(x))

@variables z::Complex{Float64}
D = Differential(z)
@show D
@show D(z)
@show expand_derivatives(D(z))
``````

yielding

``````D = Differential(x)
D(x) = Differential(x)(x)
expand_derivatives(D(x)) = 1
D = Differential(z)
D(z) = Differential(z)(z)
expand_derivatives(D(z)) = 0
``````

Bug?

2 Likes

That definitely looks like one.

@Vahid_Hosseinzadeh: are you going to report it? Else I’ll do.

This is a more nice way to see it. Thank you.

You mean issue on Github? Anyway be free to report it. Thanks @goerch

Done.

1 Like

This happens because we sneakily represent `@variables z::Complex` as `Complex{Num}(term(real, z), term(imag, z))` in order to be able to call functions restricted to `Complex{<:Real}`

It’s also unclear to me what form the answer should take in this case. @YingboMa pointed out it is possible to convert C into R^2 and differentiate, but the result is not a complex number…

You are not alone in this. Here is a different view of the same problem.

1 Like

If we use ChainRules in Symbolics, then we can propagate `Union{Jacobian2x2, Complex}`, and if we are propagating `Jacobian2x2` then convert it to `Complex` if `du_dx == du_dy` and `-du_dy == dv_dx`. We can have a list of holomorphic functions so that we don’t compute `Jacobian2x2` unnecessarily. The return type of `derivative` would be `Union{Jacobian2x2, Complex}`. Maybe we want to error if not all the elements are `Complex` when computing Jacobian and gradient.

1 Like

Thanks, that makes sense. Maybe @stevengj has a good idea for this… It would be nice to have differentiation with respect to complex numbers work in a usable way.