JuliaSymbolics / Symbolics.jl

Symbolic programming for the next generation of numerical software

Home Page:https://symbolics.juliasymbolics.org/stable/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`derivative` gives wrong answer when differentiating with respect to an expression

LilithHafner opened this issue · comments

What is the derivative of x with respect to 2x? 1/2 is a great answer. An error is good too. 0 is wrong.

julia> @variables x;

help?> Symbolics.derivative
  derivative(O, v; simplify)
  

  A helper function for computing the derivative of an expression with respect to var.

julia> Symbolics.derivative(2x, x) # correct
2

julia> Symbolics.derivative(x, 2x) # weird input, and wrong answer
0

This can be reproduces using only exported names with docstrings

help?> Differential
search: Differential

  struct Differential <: Symbolics.Operator

  Represents a differential operator.

  Fields
  ≡≡≡≡≡≡

    •  x: The variable or expression to differentiate with respect to.

  Examples
  ≡≡≡≡≡≡≡≡

  julia> using Symbolics
  
  julia> @variables x y;
  
  julia> D = Differential(x)
  (D'~x)
  
  julia> D(y) # Differentiate y wrt. x
  (D'~x)(y)
  
  julia> Dx = Differential(x) * Differential(y) # d^2/dxy operator
  (D'~x(t))  (D'~y(t))
  
  julia> D3 = Differential(x)^3 # 3rd order differential operator
  (D'~x(t))  (D'~x(t))  (D'~x(t))

help?> expand_derivatives
search: expand_derivatives

  expand_derivatives(O; ...)
  expand_derivatives(O, simplify; occurrences)
  

  TODO

  Examples
  ≡≡≡≡≡≡≡≡

  
  julia> @variables x y z k;
  
  julia> f=k*(abs(x-y)/y-z)^2
  k*((abs(x - y) / y - z)^2)
  
  julia> Dx=Differential(x) # Differentiate wrt x
  (::Differential) (generic function with 2 methods)
  
  julia> dfx=expand_derivatives(Dx(f))
  (k*((2abs(x - y)) / y - 2z)*IfElse.ifelse(signbit(x - y), -1, 1)) / y

julia> expand_derivatives(Differential(2x)(x))
0

This could be because I am misusing the expand_derivatives function. I'm happy to add a docstring if someone tells me what it it's supposed to do.

That should error. We should make sure it's a var. Could you add an error check there?