How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Introduction

Performing symbolic differentiation is a fundamental skill in mathematics, physics, engineering, and data science. In Python, the SymPy library provides a powerful and user-friendly way to compute derivatives symbolically, allowing you to manipulate and analyze mathematical expressions exactly rather than approximately. This is especially useful for tasks like:

In a previous article, we explored How to Perform Indefinite (Symbolic) Integration in Python Using SymPy, where we learned how to compute antiderivatives symbolically. In this article, we will focus on the complementary topic: symbolic differentiation, showing how to compute derivatives of functions, higher-order derivatives, partial derivatives, and more using Python and SymPy.

Install SymPy

1
pip install sympy

Basic symbolic differentiation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import sympy as sp

# Define a symbol
x = sp.symbols('x')

# Define an expression
expr = x**2 + 3*x + 5

# Differentiate with respect to x
dexpr = sp.diff(expr, x)

print(dexpr)

Output

1
2*x + 3

Higher-order derivatives

1
2
sp.diff(expr, x, 2)   # second derivative
sp.diff(expr, x, 3)   # third derivative

Partial derivatives (multivariable)

1
2
3
4
5
6
7
8
9
x, y = sp.symbols('x y')

f = x**2 * y + sp.sin(y)

df_dx = sp.diff(f, x)
df_dy = sp.diff(f, y)

print(df_dx)  # 2*x*y
print(df_dy)  # x**2 + cos(y)

Implicit differentiation

\begin{equation}
x^2 + y^2 = 1
\end{equation}

1
2
3
4
5
6
7
8
9
x = sp.symbols('x')
y = sp.Function('y')(x)

expr = x**2 + y**2 - 1

dy_dx = sp.diff(expr, x)
solution = sp.solve(dy_dx, sp.diff(y, x))[0]

print(solution)

Result

1
-x/y(x)

Symbolic derivatives of functions

1
2
3
4
x = sp.symbols('x')
f = sp.Function('f')

sp.diff(f(x), x)

Output

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Evaluate derivative at a point

1
2
3
4
5
6
7
8
# Define an expression
expr = x**2 + 3*x + 5

# Differentiate with respect to x
dexpr = sp.diff(expr, x)

    #Evaluate derivative at a point
dexpr.subs(x, 2) # Results: 7

or numerically:

1
float(dexpr.subs(x, 2)) # Results: 7.0

Convert symbolic derivative to a NumPy function

Useful for plotting or numerical work:

1
2
3
4
5
6
import numpy as np

f_num = sp.lambdify(x, dexpr, 'numpy')

xvals = np.linspace(0, 5, 100)
yvals = f_num(xvals)

You can visualize the original function alongside its derivative in a single plot, using different colors and a legend for clarity. Here’s a clear example with a symbolic expression:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import matplotlib.pyplot as plt

    # Define symbol and function
    x = sp.symbols('x')
    expr = x**2 + 3*x + 5  # original function

    # Compute derivative symbolically
    dexpr = sp.diff(expr, x)

    # Convert symbolic expressions to numerical functions
    f_num = sp.lambdify(x, dexpr, 'numpy')   # derivative
    f_orig = sp.lambdify(x, expr, 'numpy')   # original function

    # Create x values
    xvals = np.linspace(0, 5, 100)

    # Evaluate functions at these points
    yvals_deriv = f_num(xvals)
    yvals_orig = f_orig(xvals)

    # Plot both
    plt.figure(figsize=(8,5))
    plt.plot(xvals, yvals_orig, label='f(x) = x^2 + 3x + 5', color='green', linewidth=2)
    plt.plot(xvals, yvals_deriv, label="f'(x) = 2x + 3", color='blue', linewidth=2)
    plt.title("Function and Its Derivative")
    plt.xlabel("x")
    plt.ylabel("Value")
    plt.grid(True)
    plt.legend()
    # Save the figure
    plt.savefig("function_and_derivative.png", bbox_inches="tight", dpi=100)
    plt.show()

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Simplifying and Rendering Symbolic Derivatives

Once a symbolic derivative has been computed with SymPy, you may want to simplify, inspect, or render the result in a clean and readable mathematical form. SymPy provides several built-in tools to do exactly that.

Simplifying symbolic derivatives

After differentiation, expressions can sometimes be algebraically complex. You can simplify them using:

1
sp.simplify(dexpr)

This attempts to reduce the expression to a more compact and mathematically equivalent form.

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Pretty-printing in the console

To display the derivative in a more readable, textbook-style format directly in the terminal:

1
sp.pretty(dexpr)

This prints an ASCII-formatted version of the expression, which is useful outside Jupyter notebooks.

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Exporting derivatives to LaTeX

To convert a symbolic derivative into valid LaTeX code:

1
sp.latex(dexpr)

This is particularly useful for:

  • Scientific reports
  • Academic papers
  • Slides and documentation
  • Jupyter notebooks with LaTeX rendering

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Rendering SymPy Derivatives in LaTeX (Jupyter Notebook)

In a Jupyter notebook, SymPy expressions—including symbolic derivatives—can be rendered beautifully in LaTeX using built-in display tools. This significantly improves readability and presentation quality.

This enables automatic LaTeX rendering for all SymPy outputs.

1
2
3
4
5
6
7
8
9
import sympy as sp

sp.init_printing()

x = sp.Symbol('x')
f = x**2 * sp.exp(x)

df = sp.diff(f, x)
df

Output:

The derivative appears as a properly formatted LaTeX expression directly in the output cell.

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Option 2: Displaying equations with display() and sp.Eq()

To explicitly show a differentiation equation:

1
2
3
4
5
6
7
8
from sympy import symbols, diff, exp, Eq
from IPython.display import display

x = symbols('x')
f = x**2 * exp(x)
df = diff(f, x)

display(Eq(sp.Derivative(f, x), df))

This is useful for teaching or documentation, as it clearly shows the differentiation operation and its result.

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Option 3: Manual LaTeX rendering with display(Math(...))

For full control over the rendered equation:

1
2
3
from IPython.display import display, Math

display(Math(f"\\frac{{d}}{{dx}}\\left(x^2 e^x\\right) = {sp.latex(df)}"))

Here, sp.latex() converts the symbolic expression into LaTeX, while Math() handles the rendering.

Option 4 (Optional): Inline LaTeX in Markdown cells

For presentation-quality output, you can also write LaTeX directly in a Markdown cell:

1
$\frac{d}{dx}\left(x^2 e^x\right) = e^x(x^2 + 2x)$

This is ideal for tutorials, lecture notes, and static documentation.

How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?
How to Perform Symbolic (Indefinite) Derivatives in Python with SymPy ?

Common pitfalls

  • Use ** not ^
  • Always declare symbols with symbols()
  • Use sympy.sin, sympy.exp, etc. (not NumPy versions)

References

Image

of