Derivatives in Python with SymPy diff
Differentiate any expression exactly with sympy.diff, or estimate a slope numerically with a central difference.
- First and second derivatives with sp.diff
- Evaluating a derivative with subs
- A numerical derivative with a central difference
- 1
x**3 + 2*x**2 - 5*xf(x) - 2
3*x**2 + 4*x - 5f'(x) - 3
15f'(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.
f🛣️ The distance on the trip metersp.diff(f, x)🚗 The speedometer: how fast f changesdf.subs(x, 2)⏱️ Read the speed at one moment(g(at + h) - g(at - h)) / (2 * h)📏 Time the car over a tiny stretchThe 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
x = sp.symbols("x")creates a symbol that SymPy can differentiate.sp.diff(f, x)is the first derivative andsp.diff(f, x, 2)the second.df.subs(x, 2)substitutes a value and returns the exact result, 15.- 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
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}")
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Making h too small
With a tiny step like 1e-15, rounding errors swamp the result.
derivative(g, 2, h=1e-15)
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.
f = x**3 + 2x**2
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 challengesTools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.