Math and Science with Python

Derivatives in Python with SymPy diff

Differentiate any expression exactly with sympy.diff, or estimate a slope numerically with a central difference.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • First and second derivatives with sp.diff
  • Evaluating a derivative with subs
  • A numerical derivative with a central difference
Differentiating x**3 + 2*x**2 - 5*x
  1. 1x**3 + 2*x**2 - 5*xf(x)
  2. 23*x**2 + 4*x - 5f'(x)
  3. 315f'(2)

The slope at every point

The problem

A derivative tells you how fast something changes: velocity from position, a growth rate, or where a curve is flat. Differentiating long expressions by hand invites mistakes, and checking an answer takes as long as finding it.

Think of it like this

A derivative is like the speedometer in a car. The trip meter tells you how far you have gone, and the speedometer tells you how fast that number is changing right now. A central difference is like timing the car over a very short stretch of road.

From a speedometer to code
f🛣️ The distance on the trip meter
sp.diff(f, x)🚗 The speedometer: how fast f changes
df.subs(x, 2)⏱️ Read the speed at one moment
(g(at + h) - g(at - h)) / (2 * h)📏 Time the car over a tiny stretch
The exact rule and a quick measurement.
In one sentence

The derivative of f(x) is its rate of change, the slope of the curve at each point. sympy.diff finds it exactly as a formula; a central difference estimates it at one point from two nearby values.

Key points

  1. x = sp.symbols("x") creates a symbol that SymPy can differentiate.
  2. sp.diff(f, x) is the first derivative and sp.diff(f, x, 2) the second.
  3. df.subs(x, 2) substitutes a value and returns the exact result, 15.
  4. The central difference (g(at + h) - g(at - h)) / (2 * h) works for any Python function.

When should you use it?

  • Velocity and acceleration from a position formula.
  • Finding maximum and minimum points where the slope is 0.
  • Checking derivatives in calculus homework.

When not to use it

  • Gradients for machine learning models: libraries like PyTorch or JAX compute them automatically.
  • Noisy measured data: a plain difference amplifies the noise; smooth the data first.

Example code

Open in editor →
main.py
import math
import sympy as sp

# Exact derivatives with SymPy
x = sp.symbols("x")
f = x**3 + 2*x**2 - 5*x
df = sp.diff(f, x)          # first derivative
d2f = sp.diff(f, x, 2)      # second derivative
print("f(x)   =", f)
print("f'(x)  =", df)
print("f''(x) =", d2f)
print("f'(2)  =", df.subs(x, 2))
print("d/dx sin(x)*exp(x) =", sp.diff(sp.sin(x) * sp.exp(x), x))

# Numerical derivative with a central difference
def derivative(g, at, h=1e-5):
    return (g(at + h) - g(at - h)) / (2 * h)

g = lambda t: t**3 + 2*t**2 - 5*t
print(f"Numerical f'(2) = {derivative(g, 2):.6f}")
print(f"Numerical sin'(0) = {derivative(math.sin, 0):.6f}")
Get a Run button for this example

Result of running the code

f(x)   = x**3 + 2*x**2 - 5*x
f'(x)  = 3*x**2 + 4*x - 5
f''(x) = 2*(3*x + 2)
f'(2)  = 15
d/dx sin(x)*exp(x) = exp(x)*sin(x) + exp(x)*cos(x)
Numerical f'(2) = 15.000000
Numerical sin'(0) = 1.000000

Code explanation

sp.diff(f, x) differentiates f = x**3 + 2*x**2 - 5*x and returns 3*x**2 + 4*x - 5; sp.diff(f, x, 2) gives the second derivative, which SymPy prints factored as 2*(3*x + 2). df.subs(x, 2) puts 2 in for x, giving 15. The derivative() function needs no SymPy: it measures the slope between at - h and at + h with a tiny h, and gets the same 15.000000 for f'(2) and 1.000000 for the slope of sin at 0.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Making h too small

With a tiny step like 1e-15, rounding errors swamp the result.

Problem
derivative(g, 2, h=1e-15)
Fix
derivative(g, 2, h=1e-5)

Forgetting the * between a number and a symbol

Python reads 2x as a syntax error; SymPy needs explicit multiplication.

Problem
f = x**3 + 2x**2
Fix
f = x**3 + 2*x**2

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson