How to Derivative of piecewise functions using SymPy

As an example, I have the following piecewise function

using SymPy
@syms x
f(x) = (0 <= x <=10 ? 2*x : 3*x^2)

I tried to differentiate f(x) with respect to x

df = sympy.diff(f(x),x)

It results to non piecewise function 6*x which is valid only when x is not in the range [0; 10].

Please help me.

Thank you.

You would need to use sympy.Piecewise, as in:

diff(sympy.Piecewise((2x, (Ge(0,x) & Le(x, 10))), (3x^2, true)), x)

The regular Boolean operations in Julia eagerly evaluate, so x < 0 resolves to essentially Lt(x,0) == true rather than just Lt(x,0).

2 Likes