Sympy is generally a great tool for calculating both the integral and derivative of a function. When the function happens to contain an absolute component though (|x|), for some reason it doesn't seem to be able to figure that out.
when for example you write something like this:
diff(abs(x+1))
you'll get the following output:
sign(x+1)
The answer shoud be (x+1)/|x+1|, so is there something wrong with sympy and is there a way around it?
In SymPy sign(z)
is defined as z/|z|
for complex non-zero z
. In fact another definition of sign(z)
is precisely as the derivative of abs(z)
:
https://en.wikipedia.org/wiki/Sign_function#Definition
It should ideally be possible to use rewrite(Abs)
with sign
but is not currently:
https://github.com/sympy/sympy/issues/19277
Note that rewrite wouldn't work in your case without any way to know that x+1
is nonzero (e.g. if x
is declared as positive`).
You can force the rewrite manually using replace
though:
In [4]: s
Out[4]: sign(x + 1)
In [5]: s.replace(sign, lambda arg: arg/Abs(arg))
Out[5]:
x + 1
───────
│x + 1│