The Derivative
The derivative measures how fast a function changes: the slope of its graph at a single point, or the instantaneous rate of change of one quantity with respect to another. Speed is the derivative of position, marginal cost is the derivative of cost, and a gradient in machine learning is a bundle of derivatives.
From secant to tangent
The average rate of change of between and is the slope of the secant line through those two points. Let shrink to 0 and the secant turns into the tangent line. Its slope is the derivative:
Other notations you will meet: , , , , and for derivatives with respect to time. The tangent line at is
Working it out from the definition
For :
So . At the slope is 6, and the tangent is . SymPy can do the limit for us, and sp.diff gives the same result directly:
import sympy as sp
x, h = sp.symbols('x h')
f = x**3 - 2 * x
quotient = (f.subs(x, x + h) - f) / h
print("difference quotient:", sp.expand(sp.simplify(quotient)))
print("limit h -> 0 :", sp.limit(quotient, h, 0))
print("sp.diff :", sp.diff(f, x))
print("slope at x = 2 :", sp.diff(f, x).subs(x, 2))difference quotient: h**2 + 3*h*x + 3*x**2 - 2
limit h -> 0 : 3*x**2 - 2
sp.diff : 3*x**2 - 2
slope at x = 2 : 10
Numeric evidence: shrinking h
The same derivative from numbers alone. For at the exact slope is :
def f(x):
return x**3 - 2 * x
print(" h forward diff error")
for k in range(1, 8):
h = 10.0**-k
d = (f(2 + h) - f(2)) / h
print(f"{h:9.0e} {d:15.10f} {abs(d - 10):.2e}") h forward diff error
1e-01 10.6100000000 6.10e-01
1e-02 10.0601000000 6.01e-02
1e-03 10.0060010000 6.00e-03
1e-04 10.0006000100 6.00e-04
1e-05 10.0000600002 6.00e-05
1e-06 10.0000060019 6.00e-06
1e-07 10.0000005876 5.88e-07
The error shrinks roughly in proportion to : one more zero in , one more correct digit. That is a first-order method.
Why h too small fails in floating point
In exact arithmetic smaller is always better. On a computer it is not. A 64-bit float has about 16 significant digits (machine epsilon ). When is tiny, and agree in almost all their digits, and subtracting them leaves mostly rounding noise (catastrophic cancellation). That noise is then divided by the tiny , which magnifies it.
The two terms balance near for the forward difference. The central difference has truncation error proportional to , so it is more accurate and its best is near .
import numpy as np
import matplotlib.pyplot as plt
x0, exact = 1.0, np.cos(1.0) # d/dx sin x = cos x
hs = 10.0 ** -np.arange(1, 16)
fwd = np.abs((np.sin(x0 + hs) - np.sin(x0)) / hs - exact)
cen = np.abs((np.sin(x0 + hs) - np.sin(x0 - hs)) / (2 * hs) - exact)
for h, e1, e2 in zip(hs[::2], fwd[::2], cen[::2]):
print(f"h = {h:.0e} forward error {e1:.1e} central error {e2:.1e}")
plt.figure(figsize=(6, 4))
plt.loglog(hs, fwd, "o-", label="forward")
plt.loglog(hs, cen, "s-", label="central")
plt.xlabel("step h"); plt.ylabel("absolute error")
plt.title("Finite-difference error for d/dx sin(x) at x = 1")
plt.legend(); plt.grid(True, which="both", alpha=0.3)h = 1e-01 forward error 4.3e-02 central error 9.0e-04
h = 1e-03 forward error 4.2e-04 central error 9.0e-08
h = 1e-05 forward error 4.2e-06 central error 1.1e-11
h = 1e-07 forward error 4.2e-08 central error 1.9e-10
h = 1e-09 forward error 5.3e-08 central error 3.0e-09
h = 1e-11 forward error 1.2e-06 central error 1.2e-06
h = 1e-13 forward error 7.3e-04 central error 1.8e-04
h = 1e-15 forward error 1.5e-02 central error 1.5e-02
The V shape is the whole story: to the right, truncation error dominates; to the left, rounding error takes over and the "more precise" step gets worse.
In software
- Gradient checking: when you write a backward pass by hand, you compare it with central differences at . If they disagree beyond a relative error of about , the hand-written gradient has a bug.
- Automatic differentiation (PyTorch, JAX) avoids both truncation and cancellation by applying the derivative rules of the next lessons to every operation; see Automatic Differentiation.
- Physics and animation: velocity is the derivative of position. Estimating it as is a backward difference, with the same error trade-offs.
- Rates in monitoring: "requests per second" graphs are difference quotients of a counter over a window: a bigger window is smoother but less instantaneous.
Exercises
Exercise 1: From the definition
Use the limit definition to find the derivative of .
Answer
Solution
Exercise 2: Tangent line
Find the tangent line to at . (Its derivative is .)
Answer
Solution
Exercise 3: Average versus instantaneous
A file downloads so that after seconds MB have arrived. Find the average rate over and the instantaneous rate at .
Answer
Both are 3 MB/s.
Solution
For a parabola the secant slope over an interval equals the tangent slope at the midpoint.
Exercise 4: Find the best h
For at (exact derivative ), find which gives the smallest forward-difference error.
Answer
h = 1e-08, with an error of about 7e-09.
Solution
import math
errors = {}
for k in range(1, 16):
h = 10.0**-k
d = (math.exp(1 + h) - math.exp(1)) / h
errors[h] = abs(d - math.e)
best = min(errors, key=errors.get)
print("best h:", best, " error:", f"{errors[best]:.1e}")best h: 1e-08 error: 6.6e-09
This matches the rule of thumb .
Test yourself
What does represent geometrically?
- The area under up to
- The height of the graph at
- The slope of the tangent line at
- The average of
Why does a forward difference with h = 1e-15 give a worse answer than h = 1e-8?
- The limit definition is wrong for small
- Subtracting two nearly equal floats loses digits, and dividing by tiny magnifies the rounding error
- Python cannot store 1e-15
- Truncation error grows as shrinks
The central difference has error proportional to …
- it is exact