Calculus with SymPy and NumPy
Python gives you two ways to do calculus: symbolic, with SymPy, which manipulates formulas exactly the way you would on paper, and numeric, with NumPy, which works with lots of numbers at once and gives approximate answers. This lesson shows both, plus Matplotlib for drawing graphs.
Symbolic vs numeric
| Symbolic (SymPy) | Numeric (NumPy, plain Python) | |
|---|---|---|
| Works with | formulas like x**2 + 3*x |
concrete numbers and arrays |
| Answers are | exact: sqrt(2), pi/4, 1/3 |
approximate: 1.4142135623730951 |
| Speed | slow on big problems | very fast, millions of values |
| Typical use | checking algebra, finding a derivative formula | simulations, plots, ML training, game loops |
In practice you use both: SymPy to find or check a formula, NumPy to evaluate it over many points.
SymPy basics
You first declare symbols, the variables SymPy is allowed to treat as unknowns. After that, ordinary Python operators build expressions:
import sympy as sp
x = sp.symbols('x')
f = x**3 - 6*x**2 + 9*x + 1
print("f(x) =", f)
print("f'(x) =", sp.diff(f, x))
print("f''(x) =", sp.diff(f, x, 2))
print("∫ f dx =", sp.integrate(f, x))
print("∫₀² f dx =", sp.integrate(f, (x, 0, 2)))
print("f(4) =", f.subs(x, 4))
print("roots of f' =", sp.solve(sp.diff(f, x), x))f(x) = x**3 - 6*x**2 + 9*x + 1
f'(x) = 3*x**2 - 12*x + 9
f''(x) = 6*(x - 2)
∫ f dx = x**4/4 - 2*x**3 + 9*x**2/2 + x
∫₀² f dx = 8
f(4) = 5
roots of f' = [1, 3]
SymPy prints with Python syntax: ** means a power and * means multiplication, so 3*x**2 is . It may also keep a result factored, as with 6*(x - 2), which is . The indefinite integral leaves out the ""; you add it yourself when you write it down.
| Function | What it does | Example |
|---|---|---|
sp.symbols('x y') |
create symbols | x, y = sp.symbols('x y') |
sp.diff(f, x) |
derivative | sp.diff(sp.sin(x), x) → cos(x) |
sp.integrate(f, x) |
antiderivative | sp.integrate(1/x, x) → log(x) |
sp.integrate(f, (x, a, b)) |
definite integral | area from to |
sp.limit(f, x, a) |
limit as | sp.limit(sp.sin(x)/x, x, 0) → 1 |
sp.simplify(f) |
tidy an expression | sp.simplify(sp.sin(x)**2 + sp.cos(x)**2) → 1 |
sp.solve(eq, x) |
solve eq = 0 |
sp.solve(x**2 - 4, x) → [-2, 2] |
sp.lambdify(x, f) |
turn a formula into a fast Python/NumPy function | see below |
Note: SymPy writes the natural logarithm as
log, notln, and usesoo(two letter o's) for infinity.
Limits and simplification
Limits are the foundation of the derivative. SymPy computes them exactly, even where plugging in the number would give 0/0:
import sympy as sp
x, h = sp.symbols('x h')
print(sp.limit(sp.sin(x) / x, x, 0))
print(sp.limit((1 + 1/x)**x, x, sp.oo))
print(sp.limit(((x + h)**2 - x**2) / h, h, 0))
print(sp.simplify((x**2 - 1) / (x - 1)))
print(sp.simplify(sp.sin(x)**2 + sp.cos(x)**2))1
E
2*x
x + 1
1
The third line is the derivative of computed straight from its definition, the limit of a difference quotient. E is SymPy's name for Euler's number .
From formula to numbers: lambdify
SymPy expressions are slow to evaluate point by point. sp.lambdify converts one into a normal function that accepts NumPy arrays, so you can evaluate it at thousands of points at once. Here we plot a function together with its derivative:
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
x = sp.symbols('x')
f = x**3 - 6*x**2 + 9*x + 1
df = sp.diff(f, x)
f_num = sp.lambdify(x, f, 'numpy')
df_num = sp.lambdify(x, df, 'numpy')
xs = np.linspace(-0.5, 4.5, 200)
plt.figure(figsize=(6, 4))
plt.plot(xs, f_num(xs), label="f(x)")
plt.plot(xs, df_num(xs), "--", label="f'(x)")
plt.axhline(0, color="gray", linewidth=0.8)
plt.legend()
plt.title("A cubic and its derivative")
print("f at x = 0, 1, 2, 3:", f_num(np.array([0, 1, 2, 3])))
print("f' is zero at x =", sp.solve(df, x))f at x = 0, 1, 2, 3: [1 5 3 1]
f' is zero at x = [1, 3]
Look at the picture: wherever the dashed derivative crosses zero ( and ), the cubic has a peak or a valley. That link between a function and its derivative is the core of the next chapter.
Numeric calculus without SymPy
You do not always have a formula. A sensor log, a game simulation or a neural network gives you only numbers. Then you approximate: the derivative with a small difference, the integral with a sum. NumPy has helpers for both:
import numpy as np
xs = np.linspace(0, 2, 2001) # step 0.001
ys = xs**3 - 6*xs**2 + 9*xs + 1
slopes = np.gradient(ys, xs) # numeric derivative at every point
print("slope near x = 0.5:", round(slopes[500], 4), "(exact 3.75)")
area = np.trapezoid(ys, xs) # numeric integral
print("area from 0 to 2:", round(area, 6), "(exact 8)")slope near x = 0.5: 3.75 (exact 3.75)
area from 0 to 2: 7.999999 (exact 8)
The numeric answers are very close to SymPy's exact ones, but not always identical, because they are built from finitely many points.
Tip: Use SymPy to check your algebra and to derive formulas; use NumPy when speed matters or when all you have is data. In this course most lessons show both.
In software
- Machine-learning libraries (PyTorch, JAX, TensorFlow) do neither pure symbolic nor pure numeric differentiation. They use automatic differentiation, which you will build yourself in the mini project.
- Game engines never use symbolic math at run time. They step numerically, frame by frame.
- Scientific code often derives a formula once with a computer algebra system such as SymPy, then pastes the generated code into a fast numeric program.
lambdifyandsp.ccodedo exactly this.
For more on the tools themselves see NumPy and SciPy integration.
Exercises
Exercise 1: Your first derivative
Use SymPy to find the derivative of , then evaluate it at .
Answer
, and .
Solution
import sympy as sp
x = sp.symbols('x')
g = 5*x**4 - 2*x + 7
dg = sp.diff(g, x)
print(dg)
print(dg.subs(x, 1))20*x**3 - 2
18
Each power becomes , the term becomes , and the constant 7 disappears.
Exercise 2: Exact vs approximate
Compute exactly with SymPy and approximately with np.trapezoid using 11 evenly spaced points. How large is the error?
Answer
Exact value ; the trapezoid estimate is 0.335, an error of about 0.00167.
Solution
import sympy as sp
import numpy as np
x = sp.symbols('x')
exact = sp.integrate(x**2, (x, 0, 1))
xs = np.linspace(0, 1, 11)
approx = np.trapezoid(xs**2, xs)
print(exact, round(approx, 6), round(approx - float(exact), 6))1/3 0.335 0.001667
The trapezoid rule overestimates here because curves upward, so each straight-line top sits a little above the curve.
Exercise 3: A limit that looks undefined
Find first by hand, then with SymPy.
Answer
4
Solution
import sympy as sp
x = sp.symbols('x')
print(sp.limit((x**2 - 4) / (x - 2), x, 2))4
Exercise 4: lambdify a formula
Turn into a NumPy function with lambdify, evaluate it at , and say where it seems to peak. Check with sp.solve(sp.diff(f, x), x).
Answer
Values 0, 0.3679, 0.2707, 0.1494; the peak is at .
Solution
import sympy as sp
import numpy as np
x = sp.symbols('x')
f = x * sp.exp(-x)
fn = sp.lambdify(x, f, 'numpy')
print(np.round(fn(np.array([0.0, 1.0, 2.0, 3.0])), 4))
print(sp.solve(sp.diff(f, x), x))[0. 0.3679 0.2707 0.1494]
[1]
The derivative is , which is zero only at .
Test yourself
What does sp.integrate(x**2, (x, 0, 3)) return?
- x**3/3
- 9
- 3
- 27
Why use sp.lambdify before plotting a SymPy expression?
- Matplotlib cannot draw lines otherwise
- It converts the symbolic formula into a fast function that works on NumPy arrays
- It makes the result exact
- It computes the derivative
You have only a list of measured positions of a robot every 10 ms, no formula. Which approach fits for estimating its speed?
- sp.diff
- sp.limit
- A numeric derivative such as np.gradient
- sp.simplify