TExcelTAD
Home › Calculus Essentials › The Derivative

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 ff between xx and x+hx + h is the slope of the secant line through those two points. Let hh shrink to 0 and the secant turns into the tangent line. Its slope is the derivative:

f′(x)=lim⁡h→0f(x+h)−f(x)hf'(x) = \lim_{h \to 0} \frac{f(x + h) - f(x)}{h}

Other notations you will meet: dydx\frac{dy}{dx}, dfdx\frac{df}{dx}, ddxf(x)\frac{d}{dx} f(x), DfDf, and y˙\dot{y} for derivatives with respect to time. The tangent line at x=ax = a is

y=f(a)+f′(a)⋅(x−a)y = f(a) + f'(a) \cdot (x - a)

Working it out from the definition

For f(x)=x2f(x) = x^2:

f(x+h)−f(x)h=(x+h)2−x2h=x2+2xh+h2−x2h=2x+h→2xas h→0\begin{aligned} \frac{f(x + h) - f(x)}{h} &= \frac{(x + h)^2 - x^2}{h} \\ &= \frac{x^2 + 2xh + h^2 - x^2}{h} \\ &= 2x + h \\ &\to 2x && \text{as } h \to 0 \end{aligned}

So f′(x)=2xf'(x) = 2x. At x=3x = 3 the slope is 6, and the tangent is y=9+6(x−3)=6x−9y = 9 + 6(x - 3) = 6x - 9. SymPy can do the limit for us, and sp.diff gives the same result directly:

python · try it yourself
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 f(x)=x3−2xf(x) = x^3 - 2x at x=2x = 2 the exact slope is 3⋅4−2=103 \cdot 4 - 2 = 10:

python · try it yourself
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 hh: one more zero in hh, one more correct digit. That is a first-order method.

Why h too small fails in floating point

In exact arithmetic smaller hh is always better. On a computer it is not. A 64-bit float has about 16 significant digits (machine epsilon ε≈2.2×10−16\varepsilon \approx 2.2 \times 10^{-16}). When hh is tiny, f(x+h)f(x + h) and f(x)f(x) agree in almost all their digits, and subtracting them leaves mostly rounding noise (catastrophic cancellation). That noise is then divided by the tiny hh, which magnifies it.

total error≈truncation (≈C⋅h)+rounding (≈ε⋅∣f(x)∣/h)\text{total error} \approx \text{truncation } (\approx C \cdot h) + \text{rounding } (\approx \varepsilon \cdot \lvert f(x) \rvert / h)

The two terms balance near h≈ε≈10−8h \approx \sqrt{\varepsilon} \approx 10^{-8} for the forward difference. The central difference f(x+h)−f(x−h)2h\frac{f(x + h) - f(x - h)}{2h} has truncation error proportional to h2h^2, so it is more accurate and its best hh is near ε3≈10−5\sqrt[3]{\varepsilon} \approx 10^{-5}.

python · try it yourself
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 h≈10−5h \approx 10^{-5}. If they disagree beyond a relative error of about 10−610^{-6}, 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 (posnow−posprev)/dt(\text{pos}_\text{now} - \text{pos}_\text{prev}) / dt 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 f(x)=5x2−3xf(x) = 5x^2 - 3x.

Answer

f′(x)=10x−3f'(x) = 10x - 3

Solution
f(x+h)−f(x)=5(x2+2xh+h2)−3x−3h−5x2+3x=10xh+5h2−3hdivide by h:10x+5h−3h→0:10x−3\begin{aligned} &f(x + h) - f(x) = 5(x^2 + 2xh + h^2) - 3x - 3h - 5x^2 + 3x = 10xh + 5h^2 - 3h \\ &\text{divide by } h{:} \quad 10x + 5h - 3 \\ &h \to 0{:} \quad 10x - 3 \end{aligned}

Exercise 2: Tangent line

Find the tangent line to y=1/xy = 1/x at x=2x = 2. (Its derivative is −1/x2-1/x^2.)

Answer

y=−x/4+1y = -x/4 + 1

Solution
f(2)=12,f′(2)=−14y=12−14(x−2)=−x4+12+12=−x4+1\begin{aligned} &f(2) = \tfrac{1}{2}, \quad f'(2) = -\tfrac{1}{4} \\ &y = \tfrac{1}{2} - \tfrac{1}{4}(x - 2) = -\tfrac{x}{4} + \tfrac{1}{2} + \tfrac{1}{2} = -\tfrac{x}{4} + 1 \end{aligned}

Exercise 3: Average versus instantaneous

A file downloads so that after tt seconds D(t)=0.5t2D(t) = 0.5t^2 MB have arrived. Find the average rate over [2,4][2, 4] and the instantaneous rate at t=3t = 3.

Answer

Both are 3 MB/s.

Solution
average: D(4)−D(2)2=8−22=3 MB/sD′(t)=t, so D′(3)=3 MB/s\begin{aligned} &\text{average: } \frac{D(4) - D(2)}{2} = \frac{8 - 2}{2} = 3\ \text{MB/s} \\ &D'(t) = t, \text{ so } D'(3) = 3\ \text{MB/s} \end{aligned}

For a parabola the secant slope over an interval equals the tangent slope at the midpoint.

Exercise 4: Find the best h

For f(x)=exf(x) = e^x at x=1x = 1 (exact derivative ee), find which h=10−1,…,10−15h = 10^{-1}, \ldots, 10^{-15} gives the smallest forward-difference error.

Answer

h = 1e-08, with an error of about 7e-09.

Solution
python · try it yourself
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 h≈ε≈1.5×10−8h \approx \sqrt{\varepsilon} \approx 1.5 \times 10^{-8}.

Test yourself

What does f′(a)f'(a) represent geometrically?

  1. The area under ff up to aa
  2. The height of the graph at aa
  3. The slope of the tangent line at x=ax = a
  4. The average of ff

Why does a forward difference with h = 1e-15 give a worse answer than h = 1e-8?

  1. The limit definition is wrong for small hh
  2. Subtracting two nearly equal floats loses digits, and dividing by tiny hh magnifies the rounding error
  3. Python cannot store 1e-15
  4. Truncation error grows as hh shrinks

The central difference f(x+h)−f(x−h)2h\frac{f(x+h) - f(x-h)}{2h} has error proportional to …

  1. hh
  2. 1/h1/h
  3. it is exact
  4. h2h^2