# How to Derivative of piecewise functions using SymPy

**URL:** <https://discourse.julialang.org/t/how-to-derivative-of-piecewise-functions-using-sympy/94200>\
**Category:** General Usage\
**Created:** [February 7, 2023, 12:41pm UTC](https://discourse.julialang.org/t/how-to-derivative-of-piecewise-functions-using-sympy/94200 "2023-02-07T12:41:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Firstname\_Lastname](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/firstname_lastname/32/34201_2.png) [@Firstname\_Lastname](https://discourse.julialang.org/u/Firstname_Lastname)\
**Post date:** [February 7, 2023, 12:41pm UTC](https://discourse.julialang.org/t/how-to-derivative-of-piecewise-functions-using-sympy/94200/1 "2023-02-07T12:41:45Z")

</div>

As an example, I have the following piecewise function

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

```

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

```julia
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.

---

<div class="post-metadata">

**Author:** ![j\_verzani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j_verzani/32/8551_2.png) [@j\_verzani](https://discourse.julialang.org/u/j_verzani)\
**Post date:** [February 7, 2023, 2:23pm UTC](https://discourse.julialang.org/t/how-to-derivative-of-piecewise-functions-using-sympy/94200/2 "2023-02-07T14:23:03Z")

</div>

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

```julia
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).
