Derivatives

SymPy · Practical · 9 min

Exact derivatives remove hand-algebra errors from gradients, Jacobians and sensitivity analysis.

diff(expr, x) differentiates with respect to x; the method form expr.diff(x) is identical. Higher derivatives take a count, diff(f, x, 3), and mixed partials list several variables: diff(f, x, y) is d2f/dxdy, and diff(f, x, 2, y) differentiates twice in x then once in y.

SymPy applies the chain, product and quotient rules and knows the derivatives of all built-in functions. The result is often not in the nicest form, so follow up with simplify or factor when you need readability.

Derivative(expr, x) creates an unevaluated derivative. It prints as a derivative and is useful when writing equations (for example ODEs) or showing a formula before computing it. Call .doit() to evaluate it.

Derivatives of undefined functions are also supported: with f = Function("f"), diff(f(x)**2, x) gives 2*f(x)*Derivative(f(x), x). This is how you set up differential equations.

A few practical tips:

  • For a gradient, use a list comprehension: [diff(f, v) for v in (x, y)]. For a Jacobian, use Matrix(fs).jacobian(vars).
  • Combine with lambdify to get fast numerical gradients for optimisers.

Example

from sympy import symbols, diff, Derivative, Function, sin, exp, simplify

x, y = symbols("x y")
f = x**3 * sin(x)

print(diff(f, x))              # x**3*cos(x) + 3*x**2*sin(x)
print(diff(exp(x*y), x, y))    # (x*y + 1)*exp(x*y)
print(diff(x**4, x, 3))        # 24*x

d = Derivative(x**2 + y, x)
print(d)                       # Derivative(x**2 + y, x)
print(d.doit())                # 2*x

g = Function("g")
print(diff(g(x)**2, x))        # 2*g(x)*Derivative(g(x), x)
print(simplify(diff(x / (1 + x), x)))  # (x + 1)**(-2)
print([diff(x**2 * y, v) for v in (x, y)])  # [2*x*y, x**2]

Remember

  • diff(f, x, n) for the n-th derivative; diff(f, x, y) for mixed partials
  • Derivative(...) is unevaluated until .doit()
  • Undefined functions via Function('f') let you differentiate unknowns

Check yourself

  1. What is diff(x**4, x, 2)?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html