TExcelTAD
Home › Calculus Essentials › Calculus with SymPy and NumPy

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:

python · try it yourself
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 3x23x^2. It may also keep a result factored, as with 6*(x - 2), which is 6x−126x - 12. The indefinite integral leaves out the "+C+ C"; 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 aa to bb
sp.limit(f, x, a) limit as x→ax \to a 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, not ln, and uses oo (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:

python · try it yourself
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 x2x^2 computed straight from its definition, the limit of a difference quotient. E is SymPy's name for Euler's number e≈2.71828e \approx 2.71828.

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:

python · try it yourself
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 (x=1x = 1 and x=3x = 3), 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:

python · try it yourself
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. lambdify and sp.ccode do 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 g(x)=5x4−2x+7g(x) = 5x^4 - 2x + 7, then evaluate it at x=1x = 1.

Answer

g′(x)=20x3−2g'(x) = 20x^3 - 2, and g′(1)=18g'(1) = 18.

Solution
python · try it yourself
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 xnx^n becomes n⋅xn−1n \cdot x^{n-1}, the −2x-2x term becomes −2-2, and the constant 7 disappears.

Exercise 2: Exact vs approximate

Compute ∫01x2 dx\int_0^1 x^2\,dx exactly with SymPy and approximately with np.trapezoid using 11 evenly spaced points. How large is the error?

Answer

Exact value 13\frac{1}{3}; the trapezoid estimate is 0.335, an error of about 0.00167.

Solution
python · try it yourself
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 x2x^2 curves upward, so each straight-line top sits a little above the curve.

Exercise 3: A limit that looks undefined

Find lim⁡x→2x2−4x−2\lim_{x \to 2} \frac{x^2 - 4}{x - 2} first by hand, then with SymPy.

Answer

4

Solution
x2−4x−2=(x−2)(x+2)x−2=x+2(for x≠2)x+2→4 as x→2\begin{aligned} \frac{x^2 - 4}{x - 2} &= \frac{(x - 2)(x + 2)}{x - 2} = x + 2 && (\text{for } x \ne 2) \\ x + 2 &\to 4 \text{ as } x \to 2 \end{aligned}
python · try it yourself
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 f(x)=x⋅e−xf(x) = x \cdot e^{-x} into a NumPy function with lambdify, evaluate it at x=0,1,2,3x = 0, 1, 2, 3, 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 x=1x = 1.

Solution
python · try it yourself
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 e−x−x⋅e−x=(1−x)e−xe^{-x} - x \cdot e^{-x} = (1 - x)e^{-x}, which is zero only at x=1x = 1.

Test yourself

What does sp.integrate(x**2, (x, 0, 3)) return?

  1. x**3/3
  2. 9
  3. 3
  4. 27

Why use sp.lambdify before plotting a SymPy expression?

  1. Matplotlib cannot draw lines otherwise
  2. It converts the symbolic formula into a fast function that works on NumPy arrays
  3. It makes the result exact
  4. 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?

  1. sp.diff
  2. sp.limit
  3. A numeric derivative such as np.gradient
  4. sp.simplify