Course contents 07 / 16

07 / 16 · Calculus

Derivatives and Taylor series

The derivative as the best linear approximation of a function, the chain rule, Taylor polynomials with an explicit remainder, what the first two derivatives tell an optimizer, and how finite differences trade truncation against rounding.

On this page 7

What is 4.1\sqrt{4.1}, without a calculator? The square root is curved, yet near 4 it is almost a line: it rises by about a quarter of each small step, so 4.1≈2+0.25⋅0.1=2.025\sqrt{4.1} \approx 2 + 0.25 \cdot 0.1 = 2.025. The true value is 2.0248462.024846. The guess is off by 1.5⋅10−41.5 \cdot 10^{-4}, and halving the step makes the error four times smaller.

Every loss in machine learning is built like this function: from exponentials, logarithms and products of weights, none of them linear. Yet near any point a smooth function is almost linear, and the linear algebra of the previous notes applies to that linear part. How good is the linear guess, how do we add curvature to it, and how does a computer find the slope when it has only the function’s values?

The derivative as the best linear approximation#

The slope of the line through (x,f(x))(x, f(x)) and (x+h,f(x+h))(x + h, f(x + h)) is the difference quotient (f(x+h)−f(x))/h\big(f(x + h) - f(x)\big)/h. For f(x)=x2f(x) = x^2 at x=1x = 1 it is ((1+h)2−1)/h=2+h\big((1 + h)^2 - 1\big)/h = 2 + h: 2.12.1 for h=0.1h = 0.1 and 2.012.01 for h=0.01h = 0.01. The derivative f′(x)f'(x) is its limit as h→0h \to 0, here f′(1)=2f'(1) = 2.

The limit hides what the derivative is for, which is replacing a curve by a line. Rewritten, the definition says that ff is differentiable at xx when, near xx, it equals a linear function of the increment plus an error that is small compared with the increment:

f(x+h)=f(x)+f′(x) h+r(h),r(h)h→0as h→0.\begin{aligned} f(x + h) &= f(x) + f'(x)\, h + r(h), \\ \frac{r(h)}{h} &\to 0 \quad \text{as } h \to 0 . \end{aligned}

The two definitions agree, because dividing the error by hh gives

r(h)h=f(x+h)−f(x)h−f′(x),\frac{r(h)}{h} = \frac{f(x + h) - f(x)}{h} - f'(x) ,

which tends to 0 exactly when the difference quotient tends to f′(x)f'(x). A quantity is written o(h)o(h) when, divided by hh, it tends to 0, and O(hk)O(h^k) when it is at most a constant times ∣h∣k\lvert h\rvert^k for small hh. So f(x+h)=f(x)+f′(x)h+o(h)f(x + h) = f(x) + f'(x)h + o(h).

The tangent is the best line through (x,f(x))(x, f(x)). Any other slope mm leaves the error (f′(x)−m) h+r(h)(f'(x) - m)\, h + r(h), which divided by hh tends to f′(x)−m≠0f'(x) - m \ne 0. Another line misses by an amount proportional to hh; the tangent misses by less than any multiple of hh.

Example. For f(x)=xf(x) = \sqrt x at 4, f′(4)=1/(24)=0.25f'(4) = 1/(2\sqrt4) = 0.25:

step hhtangent 2+h/42 + h/44+h\sqrt{4 + h}error−h2/64-h^2/64
0.10.12.0252.0252.0248462.024846−1.54⋅10−4-1.54 \cdot 10^{-4}−1.56⋅10−4-1.56 \cdot 10^{-4}
0.050.052.01252.01252.0124612.012461−3.88⋅10−5-3.88 \cdot 10^{-5}−3.91⋅10−5-3.91 \cdot 10^{-5}

The error falls like h2h^2, and to leading order it is 12f′′(4) h2=−h2/64\tfrac12 f''(4)\,h^2 = -h^2/64, the last column. Taylor’s theorem below explains why.

The rules, and the chain rule derived#

Four derivatives come straight from the definition. For xnx^n the binomial expansion gives ((x+h)n−xn)/h=nxn−1+O(h)\big((x + h)^n - x^n\big)/h = nx^{n-1} + O(h). The number ee is defined as the base for which (eh−1)/h→1(e^h - 1)/h \to 1, so (ex+h−ex)/h=ex(eh−1)/h→ex(e^{x+h} - e^x)/h = e^x(e^h - 1)/h \to e^x. For sin⁡\sin, the addition formula and the limits sin⁡h/h→1\sin h/h \to 1, (cos⁡h−1)/h→0(\cos h - 1)/h \to 0 give cos⁡\cos. And (log⁡x)′=1/x(\log x)' = 1/x follows by differentiating elog⁡x=xe^{\log x} = x with the chain rule below (Strang and Herman, 2016a, theorems 3.3, 3.8, 3.14 and 3.15).

Three rules build the rest from them. Linearity, (af+bg)′=af′+bg′(af + bg)' = af' + bg', holds because the linear parts of ff and gg add. The product rule, (fg)′=f′g+fg′(fg)' = f'g + fg', comes from multiplying the two approximations: (f+f′h+rf)(g+g′h+rg)=fg+(f′g+fg′) h+o(h)(f + f'h + r_f)(g + g'h + r_g) = fg + (f'g + fg')\,h + o(h), since every other product contains h2h^2, rfr_f or rgr_g and is o(h)o(h). The third, for a composition, is the chain rule:

(g∘f)′(x)=g′(f(x)) f′(x).\big(g \circ f\big)'(x) = g'\big(f(x)\big)\, f'(x) .

It composes the two linear approximations. A step hh in xx moves f(x)f(x) by about f′(x) hf'(x)\,h, and that step moves gg by about g′(f(x))g'(f(x)) times it. To make this exact, write y=f(x)y = f(x) and k=f(x+h)−f(x)k = f(x + h) - f(x), the step that hh causes in the input of gg. Differentiability of gg at yy can be written as g(y+k)−g(y)=(g′(y)+ε(k)) kg(y + k) - g(y) = \big(g'(y) + \varepsilon(k)\big)\,k with ε(k)→0\varepsilon(k) \to 0 as k→0k \to 0 and ε(0)=0\varepsilon(0) = 0; this form allows k=0k = 0, which can happen for h≠0h \ne 0. Then

g(f(x+h))−g(f(x))h=g(y+k)−g(y)h=(g′(y)+ε(k)) kh→g′(y) f′(x).\begin{aligned} \frac{g(f(x + h)) - g(f(x))}{h} &= \frac{g(y + k) - g(y)}{h} \\ &= \big(g'(y) + \varepsilon(k)\big)\, \frac{k}{h} \\ &\to g'(y)\, f'(x) . \end{aligned}

In the limit k/h→f′(x)k/h \to f'(x) by differentiability of ff, and k=f′(x)h+r(h)→0k = f'(x)h + r(h) \to 0, so ε(k)→0\varepsilon(k) \to 0. The quotient rule follows from the product rule and the chain rule applied to 1/g1/g.

Example: the sigmoid. σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}) is g(f(x))g(f(x)) with the inner function f(x)=1+e−xf(x) = 1 + e^{-x} and the outer g(v)=1/vg(v) = 1/v, whose derivatives are f′(x)=−e−xf'(x) = -e^{-x} and g′(v)=−1/v2g'(v) = -1/v^2. So

σ′(x)=−1(1+e−x)2⋅(−e−x)=11+e−x⋅e−x1+e−x=σ(x)(1−σ(x)).\begin{aligned} \sigma'(x) &= -\frac{1}{(1 + e^{-x})^2} \cdot \big(-e^{-x}\big) \\ &= \frac{1}{1 + e^{-x}} \cdot \frac{e^{-x}}{1 + e^{-x}} \\ &= \sigma(x)\big(1 - \sigma(x)\big) . \end{aligned}

At x=1x = 1, σ(1)=0.7311\sigma(1) = 0.7311 and σ′(1)=0.7311⋅0.2689=0.1966\sigma'(1) = 0.7311 \cdot 0.2689 = 0.1966; a central difference with h=10−5h = 10^{-5} gives the same six digits (Code section). Backpropagation applies this rule once per node of a computation, from the loss backwards, and the one-unit example of the backpropagation note multiplies exactly this local derivative.

Taylor polynomials and the remainder#

The tangent matches the value and the slope of ff at a point aa. Matching the second, third, up to the nn-th derivative as well gives a polynomial that hugs ff more closely. The Taylor polynomial of order nn at aa is

Tn(x)=∑k=0nf(k)(a)k! (x−a)k=f(a)+f′(a)(x−a)+⋯+f(n)(a)n!(x−a)n,\begin{aligned} T_n(x) &= \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!}\, (x - a)^k \\ &= f(a) + f'(a)(x - a) + \dots + \frac{f^{(n)}(a)}{n!}(x - a)^n , \end{aligned}

where f(k)f^{(k)} is the kk-th derivative. It is the only polynomial of degree at most nn whose first nn derivatives at aa equal those of ff: the kk-th derivative of (x−a)j/j!(x - a)^j/j! at x=ax = a is 1 when j=kj = k and 0 otherwise, so each coefficient is forced. T1T_1 is the tangent.

How far is TnT_n from ff? Taylor’s theorem answers with the next derivative. If ff has n+1n + 1 continuous derivatives on an interval containing aa and xx, then for some ξ\xi between aa and xx

f(x)=Tn(x)+Rn(x),Rn(x)=f(n+1)(ξ)(n+1)! (x−a)n+1.\begin{aligned} f(x) &= T_n(x) + R_n(x), \\ R_n(x) &= \frac{f^{(n+1)}(\xi)}{(n + 1)!}\, (x - a)^{n+1} . \end{aligned}

This is the remainder in Lagrange form. The theorem holds under weaker assumptions too: a proof by Rolle’s theorem needs only that f(n+1)f^{(n+1)} exist (Strang and Herman, 2016b, theorem 6.7). With nn derivatives at aa alone, one still gets the Peano form Rn(x)=o((x−a)n)R_n(x) = o\big((x - a)^n\big), which says how fast the error vanishes but not how large it is.

Proof: the Lagrange form by Rolle’s theorem, and the Peano form

Rolle’s theorem: a function continuous on [a,b][a, b], differentiable inside, with equal values at the ends, has a zero derivative somewhere inside. Unless it is constant, its maximum or its minimum lies inside, and there the derivative vanishes (Strang and Herman, 2016a, theorems 4.1, 4.2 and 4.4). The mean value theorem, f(b)−f(a)=f′(c)(b−a)f(b) - f(a) = f'(c)(b - a), is Rolle applied to ff minus its chord (theorem 4.5).

Lagrange. Fix xx and choose KK with g(x)=0g(x) = 0 for g(t)=f(t)−Tn(t)−K(t−a)n+1g(t) = f(t) - T_n(t) - K(t - a)^{n+1}. Since TnT_n matches the first nn derivatives, g(a)=g′(a)=⋯=g(n)(a)=0g(a) = g'(a) = \dots = g^{(n)}(a) = 0. Rolle on [a,x][a, x] gives g′(ξ1)=0g'(\xi_1) = 0, Rolle on [a,ξ1][a, \xi_1] gives g′′(ξ2)=0g''(\xi_2) = 0, and so on up to g(n+1)(ξ)=f(n+1)(ξ)−(n+1)! K=0g^{(n+1)}(\xi) = f^{(n+1)}(\xi) - (n + 1)!\,K = 0. So K=f(n+1)(ξ)/(n+1)!K = f^{(n+1)}(\xi)/(n + 1)!, and Rn(x)=K(x−a)n+1R_n(x) = K(x - a)^{n+1} is the Lagrange form.

Peano. Here R=f−TnR = f - T_n has R(a)=⋯=R(n)(a)=0R(a) = \dots = R^{(n)}(a) = 0. By induction on nn, such an RR is o((x−a)n)o\big((x - a)^n\big); for n=1n = 1 this is the definition of R′(a)=0R'(a) = 0. For the step, R′R' satisfies the claim for n−1n - 1. Given ϵ>0\epsilon > 0, the mean value theorem gives, for xx close enough to aa and some ξ\xi between aa and xx, ∣R(x)∣=∣R′(ξ)∣ ∣x−a∣≤ϵ∣ξ−a∣n−1∣x−a∣≤ϵ∣x−a∣n\lvert R(x)\rvert = \lvert R'(\xi)\rvert\,\lvert x - a\rvert \le \epsilon\lvert\xi - a\rvert^{n-1}\lvert x - a\rvert \le \epsilon\lvert x - a\rvert^n.

We prove the theorem through an exact formula for the remainder,

Rn(x)=∫axf(n+1)(t) (x−t)nn! dt,R_n(x) = \int_a^x f^{(n+1)}(t)\, \frac{(x - t)^n}{n!}\, dt ,

by induction on nn. For n=0n = 0 it is the fundamental theorem of calculus, f(x)=f(a)+∫axf′(t) dtf(x) = f(a) + \int_a^x f'(t)\,dt. Assume it for n−1n - 1 and integrate Rn−1R_{n-1} by parts, differentiating f(n)(t)f^{(n)}(t) and integrating (x−t)n−1/(n−1)!(x - t)^{n-1}/(n-1)!, whose antiderivative in tt is −(x−t)n/n!-(x - t)^n/n!:

Rn−1(x)=∫axf(n)(t) (x−t)n−1(n−1)! dt=[−f(n)(t) (x−t)nn!]t=at=x+Rn(x)=f(n)(a)n! (x−a)n+Rn(x).\begin{aligned} R_{n-1}(x) &= \int_a^x f^{(n)}(t)\, \frac{(x - t)^{n-1}}{(n-1)!}\, dt \\ &= \Big[-f^{(n)}(t)\, \frac{(x - t)^n}{n!}\Big]_{t=a}^{t=x} + R_n(x) \\ &= \frac{f^{(n)}(a)}{n!}\,(x - a)^n + R_n(x) . \end{aligned}

The bracket vanishes at t=xt = x, and its value at t=at = a is the next term of the Taylor polynomial. So f=Tn−1+Rn−1=Tn+Rnf = T_{n-1} + R_{n-1} = T_n + R_n, which completes the induction.

The Lagrange form follows from the integral. The weight (x−t)n(x - t)^n keeps one sign for tt between aa and xx. So the integral lies between mm and MM times ∫ax(x−t)n/n! dt\int_a^x (x - t)^n/n!\,dt, where mm and MM are the minimum and maximum of the continuous f(n+1)f^{(n+1)} on the interval. By the intermediate value theorem, f(n+1)f^{(n+1)} takes the value in between at some point ξ\xi (Strang and Herman, 2016a, theorems 4.1 and 2.11):

Rn(x)=f(n+1)(ξ)∫ax(x−t)nn! dt=f(n+1)(ξ) (x−a)n+1(n+1)!.\begin{aligned} R_n(x) &= f^{(n+1)}(\xi) \int_a^x \frac{(x - t)^n}{n!}\, dt \\ &= f^{(n+1)}(\xi)\, \frac{(x - a)^{n+1}}{(n + 1)!} . \end{aligned}

As x→ax \to a the remainder is O((x−a)n+1)O\big((x - a)^{n+1}\big): each extra order buys one more power of the distance.

Example: exe^x. All derivatives of exe^x are exe^x, so at a=0a = 0 the polynomial is Tn(x)=1+x+x2/2+⋯+xn/n!T_n(x) = 1 + x + x^2/2 + \dots + x^n/n!, and the remainder at x=1x = 1 is eξ/(n+1)!e^\xi/(n + 1)! with 0<ξ<10 < \xi < 1. The theorem traps the error between 1/(n+1)!1/(n + 1)! and e/(n+1)!e/(n + 1)!:

nnTn(1)T_n(1)error e−Tn(1)e - T_n(1)1/(n+1)!1/(n+1)!e/(n+1)!e/(n+1)!
1220.7180.7180.5000.5001.3591.359
22.52.50.2180.2180.1670.1670.4530.453
32.66672.66670.05160.05160.04170.04170.1130.113
42.708332.708330.009950.009950.008330.008330.02270.0227

The factorial grows faster than any power, so for exe^x the remainder goes to 0 at every xx. Indeed ∣Rn(x)∣≤e∣x∣∣x∣n+1/(n+1)!\lvert R_n(x)\rvert \le e^{\lvert x\rvert}\lvert x\rvert^{n+1}/(n + 1)!, and once k>2∣x∣k > 2\lvert x\rvert, each further factor ∣x∣/k\lvert x\rvert/k of ∣x∣n+1/(n+1)!\lvert x\rvert^{n+1}/(n + 1)! is below 12\tfrac12. So the Taylor series ∑kxk/k!\sum_k x^k/k! converges to exe^x everywhere.

Example: log⁡(1+x)\log(1 + x). The kk-th derivative is (−1)k−1(k−1)!/(1+x)k(-1)^{k-1}(k - 1)!/(1 + x)^k, so at a=0a = 0 the coefficients are (−1)k−1/k(-1)^{k-1}/k and Tn(x)=x−x2/2+x3/3−…T_n(x) = x - x^2/2 + x^3/3 - \dots. For x≥0x \ge 0 the Lagrange remainder is

∣Rn(x)∣=n!(1+ξ)n+1⋅xn+1(n+1)!=xn+1(n+1)(1+ξ)n+1≤xn+1n+1,\begin{aligned} \lvert R_n(x)\rvert &= \frac{n!}{(1 + \xi)^{n+1}} \cdot \frac{x^{n+1}}{(n + 1)!} \\ &= \frac{x^{n+1}}{(n + 1)(1 + \xi)^{n+1}} \le \frac{x^{n+1}}{n + 1} , \end{aligned}

because (1+ξ)n+1≥1(1 + \xi)^{n+1} \ge 1. At x=0.1x = 0.1, where log⁡1.1=0.0953102\log 1.1 = 0.0953102:

nnerror log⁡1.1−Tn(0.1)\log 1.1 - T_n(0.1)bound 0.1n+1/(n+1)0.1^{n+1}/(n + 1)
1−4.69⋅10−3-4.69 \cdot 10^{-3}5.0⋅10−35.0 \cdot 10^{-3}
23.10⋅10−43.10 \cdot 10^{-4}3.3⋅10−43.3 \cdot 10^{-4}
3−2.32⋅10−5-2.32 \cdot 10^{-5}2.5⋅10−52.5 \cdot 10^{-5}
41.85⋅10−61.85 \cdot 10^{-6}2.0⋅10−62.0 \cdot 10^{-6}

Each order gains about one digit, a factor x=0.1x = 0.1. At x=1.8x = 1.8 the same polynomials give 1.81.8, 0.180.18, 2.1242.124 and −0.500-0.500, swinging further from log⁡2.8=1.030\log 2.8 = 1.030 at every order. The terms xk/kx^k/k grow when x>1x > 1. A series whose terms do not tend to 0 diverges, and the bound grows with the terms. A Taylor polynomial is a local statement.

Figure

The tangent and Taylor polynomials of increasing order

log(1 + x) and its Taylor polynomials of orders one to fourThe logarithm curve and four polynomials touching it at zero. Left of the line x = 1 the polynomials close in on the curve; right of it they fan out.−0.500.511.52−2−112x = 1the series divergeslog(1 + x)T₁, the tangentT₂T₃T₄log(1 + x) and its Taylor polynomials of orders one to fourThe logarithm curve and four polynomials touching it at zero. Left of the line x = 1 the polynomials close in on the curve; right of it they fan out.−0.500.511.52−2−112x = 1fT₁T₂T₃T₄
log(1 + x) (black) and its Taylor polynomials T₁ to T₄ at 0. Near 0 each order is closer: at x = 0.1 the errors are −4.7·10⁻³, 3.1·10⁻⁴, −2.3·10⁻⁵ and 1.9·10⁻⁶. Beyond x = 1 the series diverges, and the polynomials swing further away with each order.

Libraries use Taylor polynomials to evaluate functions near a point where the direct formula loses digits. For x=10−10x = 10^{-10}, rounding 1+x1 + x to a double moves it by up to u=1.1⋅10−16u = 1.1 \cdot 10^{-16}, half the spacing of doubles near 1. Since log⁡(1+x)≈x\log(1 + x) \approx x and the slope of log⁡\log there is 1, the result inherits that error, up to u/x=1.1⋅10−6u/x = 1.1 \cdot 10^{-6} relative; here it comes out as 8⋅10−88 \cdot 10^{-8}. Near 0 the series says log⁡(1+x)=x−x2/2+…\log(1 + x) = x - x^2/2 + \dots, and the library function log1p computes it to full precision; expm1 does the same for ex−1e^x - 1.

In machine learning the second-order expansion of a log-density around its maximum is the Laplace approximation, and the expansion of a loss around the current weights is the starting point of every optimizer.

Why first and second order matter for optimization#

The first-order term says in which direction ff decreases and how fast; the second-order term says for how long the decrease lasts. Take a gradient step x→x−ηf′(x)x \to x - \eta f'(x) with step size η>0\eta > 0 on a function whose second derivative is bounded, ∣f′′∣≤L\lvert f''\rvert \le L. Write g=f′(x)g = f'(x) and expand with Taylor’s theorem for n=1n = 1 and h=−ηgh = -\eta g; the bound on f′′f'' then turns the one unknown factor into a guarantee:

f(x−ηg)=f(x)−ηg2+12f′′(ξ) η2g2≤f(x)−ηg2+12Lη2g2f′′(ξ)≤L=f(x)−η(1−Lη2) g2.\begin{aligned} f(x - \eta g) &= f(x) - \eta g^2 + \tfrac12 f''(\xi)\, \eta^2 g^2 \\ &\le f(x) - \eta g^2 + \tfrac12 L\eta^2 g^2 && f''(\xi) \le L \\ &= f(x) - \eta\Big(1 - \frac{L\eta}{2}\Big)\, g^2 . \end{aligned}

For 0<η<2/L0 < \eta < 2/L the bracket is positive, and every step with f′(x)≠0f'(x) \ne 0 lowers ff. A line search turns this into a test: it accepts a step when the actual decrease is at least a fixed fraction of the first-order prediction ηg2\eta g^2 (Merkulov, 2024, lecture 2). The same bound, with LL the largest eigenvalue of the Hessian, gives the step-size limit of gradient descent.

The second-order term also gives a better step. Minimizing the quadratic model f(x)+f′(x)h+12f′′(x)h2f(x) + f'(x)h + \tfrac12 f''(x) h^2 over hh, when f′′(x)>0f''(x) > 0, gives f′(x)+f′′(x) h=0f'(x) + f''(x)\,h = 0, and Newton’s step h=−f′(x)/f′′(x)h = -f'(x)/f''(x): a gradient step whose size is set by the curvature.

At a critical point, where f′(x∗)=0f'(x^*) = 0, Taylor with n=1n = 1 reads f(x∗+h)−f(x∗)=12f′′(ξ) h2f(x^* + h) - f(x^*) = \tfrac12 f''(\xi)\, h^2. If f′′(x∗)>0f''(x^*) > 0, then f′′>0f'' > 0 near x∗x^* by continuity, and x∗x^* is a strict local minimum; if f′′(x∗)<0f''(x^*) < 0, a strict local maximum. If f′′(x∗)=0f''(x^*) = 0 the test says nothing: x3x^3, x4x^4 and −x4-x^4 all have f′=f′′=0f' = f'' = 0 at 0, and the first has no extremum there, the second a minimum and the third a maximum.

Example. f(x)=ex−2xf(x) = e^x - 2x has f′(x)=ex−2f'(x) = e^x - 2 and f′′(x)=exf''(x) = e^x, so its minimum is at x∗=log⁡2=0.6931x^* = \log 2 = 0.6931, with f′′(x∗)=2>0f''(x^*) = 2 > 0. From x0=0x_0 = 0 the errors xk−x∗x_k - x^* are:

step kk01234
gradient descent, η=0.2\eta = 0.2−0.693-0.693−0.493-0.493−0.337-0.337−0.223-0.223−0.143-0.143
Newton−0.693-0.6930.3070.3070.04260.04269.0⋅10−49.0 \cdot 10^{-4}4.0⋅10−74.0 \cdot 10^{-7}

Near the minimum, gradient descent multiplies the error by about 1−ηf′′(x∗)=0.61 - \eta f''(x^*) = 0.6 per step. Subtracting x∗x^* from the update and applying the mean value theorem to f′f', with f′(x∗)=0f'(x^*) = 0, gives xk+1−x∗=(1−ηf′′(ξk))(xk−x∗)x_{k+1} - x^* = \big(1 - \eta f''(\xi_k)\big)(x_k - x^*) with ξk\xi_k between xkx_k and x∗x^*. Newton’s method roughly squares it, doubling the number of correct digits per step, because it uses the curvature that gradient descent ignores. The unconstrained optimization note proves Newton’s rate, and logistic regression is fitted by the many-variable Newton step.

Finite differences and their error#

When ff is available only as a program, its derivative can be approximated by a difference quotient with a small fixed hh. Taylor’s theorem gives the error of the formula, and floating point adds a second error that grows as hh shrinks. The best hh balances the two.

Truncation error#

The forward difference D+f(x)=(f(x+h)−f(x))/hD_+f(x) = \big(f(x + h) - f(x)\big)/h comes from Taylor with n=1n = 1, and the central difference D0f(x)=(f(x+h)−f(x−h))/(2h)D_0f(x) = \big(f(x + h) - f(x - h)\big)/(2h) from Taylor with n=2n = 2 at both x+hx + h and x−hx - h:

f(x±h)=f(x)±f′(x) h+12f′′(x) h2±16f′′′(ξ±) h3.\begin{aligned} f(x \pm h) = f(x) &\pm f'(x)\, h + \tfrac12 f''(x)\, h^2 \\ &\pm \tfrac16 f'''(\xi_\pm)\, h^3 . \end{aligned}

Subtracting the two expansions cancels f(x)f(x) and the h2h^2 terms. The average of f′′′(ξ+)f'''(\xi_+) and f′′′(ξ−)f'''(\xi_-) is a value f′′′(ξ)f'''(\xi) of the continuous f′′′f''' between them, by the intermediate value theorem:

f(x+h)−f(x−h)=2f′(x) h+13f′′′(ξ) h3,D0f(x)=f′(x)+16f′′′(ξ) h2.\begin{aligned} f(x + h) - f(x - h) &= 2f'(x)\, h + \tfrac13 f'''(\xi)\, h^3 , \\ D_0f(x) &= f'(x) + \tfrac16 f'''(\xi)\, h^2 . \end{aligned}

The same steps with n=1n = 1 give D+f(x)=f′(x)+12f′′(ξ) hD_+f(x) = f'(x) + \tfrac12 f''(\xi)\,h. The forward difference is first-order accurate, the central one second-order.

Rounding error#

In double precision every correctly rounded operation has a relative error of at most the unit roundoff u=2−53≈1.1⋅10−16u = 2^{-53} \approx 1.1 \cdot 10^{-16} (floating point; Higham, 2002). Assume each computed value of ff is correctly rounded, as math.exp nearly is. Then f(x+h)f(x + h) and f(x)f(x) each carry an error of at most about u∣f(x)∣u\lvert f(x)\rvert, so the numerator of a difference quotient is wrong by up to about 2u∣f(x)∣2u\lvert f(x)\rvert, and dividing by a small hh magnifies it. Subtracting two nearly equal numbers keeps their absolute error but loses most of their significant digits, the standard ill-conditioned computation of the conditioning note.

With MkM_k a bound on ∣f(k)∣\lvert f^{(k)}\rvert near xx, the total errors are at most

E+(h)=M22 h+2u∣f(x)∣h,E0(h)=M36 h2+u∣f(x)∣h.\begin{aligned} E_+(h) &= \frac{M_2}{2}\, h + \frac{2u\lvert f(x)\rvert}{h}, \\ E_0(h) &= \frac{M_3}{6}\, h^2 + \frac{u\lvert f(x)\rvert}{h} . \end{aligned}

The best step#

In each bound one term grows with hh and the other falls. The second derivative of each bound in hh is positive for h>0h > 0, so the bound is convex there, and it is smallest where its derivative in hh vanishes. For the forward difference write E+=αh+β/hE_+ = \alpha h + \beta/h, with α=M2/2\alpha = M_2/2 and β=2u∣f∣\beta = 2u\lvert f\rvert:

E+′(h)=α−β/h2=0,h+∗=β/α=2u∣f∣/M2,E+(h+∗)=2αβ=2u∣f∣M2.\begin{aligned} E_+'(h) &= \alpha - \beta/h^2 = 0, \\ h_+^* &= \sqrt{\beta/\alpha} = 2\sqrt{u\lvert f\rvert/M_2}, \\ E_+(h_+^*) &= 2\sqrt{\alpha\beta} = 2\sqrt{u\lvert f\rvert M_2} . \end{aligned}

For the central one write E0=γh2+β′/hE_0 = \gamma h^2 + \beta'/h, with γ=M3/6\gamma = M_3/6 and β′=u∣f∣\beta' = u\lvert f\rvert. At the optimum β′/h=2γh2\beta'/h = 2\gamma h^2, which gives the last line:

E0′(h)=2γh−β′/h2=0,(h0∗)3=β′/(2γ)=3u∣f∣/M3,E0(h0∗)=3γ(h0∗)2=12M3(h0∗)2.\begin{aligned} E_0'(h) &= 2\gamma h - \beta'/h^2 = 0, \\ \big(h_0^*\big)^3 &= \beta'/(2\gamma) = 3u\lvert f\rvert/M_3, \\ E_0(h_0^*) &= 3\gamma\big(h_0^*\big)^2 = \tfrac12 M_3\big(h_0^*\big)^2 . \end{aligned}

When ff and its derivatives are of order 1, the forward difference is best at h≈u≈10−8h \approx \sqrt u \approx 10^{-8} and keeps about half of the sixteen digits. The central difference is best at h≈u1/3≈10−5h \approx u^{1/3} \approx 10^{-5} and keeps about two thirds (Nocedal and Wright, 2006).

Example. f(x)=exf(x) = e^x at x=1x = 1, where f=M2=M3=ef = M_2 = M_3 = e. The forward difference has h+∗=2u=2.1⋅10−8h_+^* = 2\sqrt u = 2.1 \cdot 10^{-8} and a best error bound of 2eu=5.7⋅10−82e\sqrt u = 5.7 \cdot 10^{-8}. The central difference has h0∗=(3u)1/3=6.9⋅10−6h_0^* = (3u)^{1/3} = 6.9 \cdot 10^{-6} and a bound of e2(3u)2/3=6.5⋅10−11\tfrac e2 (3u)^{2/3} = 6.5 \cdot 10^{-11}. Measured in double precision:

step hhforward errorcentral error
10−310^{-3}1.4⋅10−31.4 \cdot 10^{-3}4.5⋅10−74.5 \cdot 10^{-7}
10−510^{-5}1.4⋅10−51.4 \cdot 10^{-5}5.9⋅10−115.9 \cdot 10^{-11}
10−610^{-6}1.4⋅10−61.4 \cdot 10^{-6}1.6⋅10−101.6 \cdot 10^{-10}
10−810^{-8}6.6⋅10−96.6 \cdot 10^{-9}6.6⋅10−96.6 \cdot 10^{-9}
10−1210^{-12}4.3⋅10−44.3 \cdot 10^{-4}2.1⋅10−42.1 \cdot 10^{-4}

Both errors fall until rounding takes over and then rise again, the central one from a lower floor and a larger step.

Figure

The error of a finite difference against the step

V-shaped error curves of the forward and central differencesLogarithmic axes: step from 10⁻¹³ to 10⁻¹, error from 10⁻¹² to 1. Both curves fall from right to left to a minimum, then rise; the central difference has a lower minimum at a larger step.10⁻¹³10⁻¹¹10⁻⁹10⁻⁷10⁻⁵10⁻³10⁻¹10⁻¹²10⁻¹⁰10⁻⁸10⁻⁶10⁻⁴10⁻²1step htruncationroundingforward differencecentral differencedashed: the boundsV-shaped error curves of the forward and central differencesLogarithmic axes: step from 10⁻¹³ to 10⁻¹, error from 10⁻¹² to 1. Both curves fall from right to left to a minimum, then rise; the central difference has a lower minimum at a larger step.10⁻¹³10⁻¹¹10⁻⁹10⁻⁷10⁻⁵10⁻³10⁻¹10⁻¹²10⁻¹⁰10⁻⁸10⁻⁶10⁻⁴10⁻²1step hforward differencecentral differencedashed: the bounds
Error of the derivative of eˣ at 1 by forward (blue) and central (red) differences in double precision, with the bounds E₊(h) and E₀(h) dashed. Truncation dominates on the right (slopes 1 and 2), rounding on the left (slope −1). Vertical lines: the optimal steps 2.1·10⁻⁸ and 6.9·10⁻⁶.

The bounds are worst cases: rounding errors partly cancel, so the measured points scatter below the lines on the rounding side. Two practical details matter. The step should be exactly representable relative to xx, so that the computed (x+h)−x(x + h) - x equals the hh we divide by; a power of two such as 2−17≈7.6⋅10−62^{-17} \approx 7.6 \cdot 10^{-6} guarantees it for x=1x = 1, since 1+2−171 + 2^{-17} is a double. And a finite-difference gradient of a function of nn variables costs n+1n + 1 or 2n2n evaluations, which is why networks are differentiated by backpropagation and checked by finite differences on a few coordinates only, as in gradient checking.

Where it breaks#

Everything above assumes smoothness, and the activations of neural networks are not smooth everywhere. Take f(x)=∣x∣f(x) = \lvert x\rvert, the shape of a ReLU’s kink, at x=10−6x = 10^{-6}, where f′(x)=1f'(x) = 1 exactly. A central difference with h=10−5h = 10^{-5} straddles the kink:

∣1.1⋅10−5∣−∣−0.9⋅10−5∣2⋅10−5=0.1.\frac{\lvert 1.1 \cdot 10^{-5}\rvert - \lvert -0.9 \cdot 10^{-5}\rvert}{2 \cdot 10^{-5}} = 0.1 .

The answer is wrong by 90%, and no rounding is involved: the Taylor expansion behind the formula does not exist across the kink. With h=10−7h = 10^{-7}, which stays on one side, the difference returns 1. A gradient check that fails near a kink says nothing about the code being checked. Points within hh of a kink are excluded from such checks, and convex analysis replaces the derivative at a kink by a set of slopes.

Smoothness is not enough for a Taylor series either. The function e−1/x2e^{-1/x^2}, extended by 0 at 0, has every derivative equal to 0 at 0, so every TnT_n is identically 0.

Proof: every derivative of e^(−1/x²) vanishes at 0

For x≠0x \ne 0, induction with the product and chain rules gives f(n)(x)=Pn(1/x) e−1/x2f^{(n)}(x) = P_n(1/x)\,e^{-1/x^2} for a polynomial PnP_n. At 0, by the definition of the derivative and f(n−1)(0)=0f^{(n-1)}(0) = 0,

f(n)(0)=lim⁡h→01hPn−1(1/h) e−1/h2=0,f^{(n)}(0) = \lim_{h \to 0}\tfrac1h P_{n-1}(1/h)\,e^{-1/h^2} = 0 ,

because with s=1/h2s = 1/h^2 every term is a power ∣h∣−j=sj/2\lvert h\rvert^{-j} = s^{j/2} times e−se^{-s}, and sj/2e−s→0s^{j/2}e^{-s} \to 0: the series of ese^s gives es≥sm/m!e^s \ge s^m/m! for any integer m>j/2m > j/2.

Its series converges everywhere, to the wrong function: at x=0.5x = 0.5 the function is e−4=0.0183e^{-4} = 0.0183. The remainder formula is still correct; its bound needs max⁡∣f(n+1)∣\max\lvert f^{(n+1)}\rvert over the whole interval, which grows too fast here, and is rarely known in practice. The bound tells how the error scales with the distance, not always its size.

What you should remember#

  • f(x+h)=f(x)+f′(x)h+o(h)f(x + h) = f(x) + f'(x)h + o(h): the derivative is the slope of the best linear approximation.
  • The chain rule (g∘f)′=g′(f(x)) f′(x)(g \circ f)' = g'(f(x))\, f'(x) composes linear approximations; backpropagation applies it node by node.
  • Taylor: f(x)=Tn(x)+f(n+1)(ξ)(x−a)n+1/(n+1)!f(x) = T_n(x) + f^{(n+1)}(\xi)(x - a)^{n+1}/(n + 1)!; each order adds a power of x−ax - a, and a series can still diverge far from aa.
  • With ∣f′′∣≤L\lvert f''\rvert \le L, a gradient step with η<2/L\eta < 2/L always decreases ff; Newton’s step −f′/f′′-f'/f'' uses the curvature.
  • Forward differences have error O(h)O(h), central O(h2)O(h^2), rounding adds O(u/h)O(u/h); the best steps are about 10−810^{-8} and 10−510^{-5}.
  • A difference across a kink is wrong however small the rounding error.

Code#

The worked examples: the tangent of x\sqrt x, the chain rule for the sigmoid, the Taylor errors of exe^x and log⁡(1+x)\log(1 + x), log1p, gradient descent against Newton, the finite-difference errors, and the two failures. Digits in the last places may vary across platforms and library versions.

import math

# the tangent of sqrt at 4: the error falls like h^2 and matches f''(4) h^2 / 2 = -h^2 / 64
for h in (0.1, 0.05):
    print(h, f'{math.sqrt(4 + h) - (2 + h / 4):.3e}', f'{-h * h / 64:.3e}')
# 0.1 -1.543e-04 -1.563e-04 | 0.05 -3.882e-05 -3.906e-05

# the chain rule: sigma'(1) = sigma(1)(1 - sigma(1)) against a central difference
sig = lambda x: 1 / (1 + math.exp(-x))
print(round(sig(1) * (1 - sig(1)), 6), round((sig(1 + 1e-5) - sig(1 - 1e-5)) / 2e-5, 6))   # 0.196612 0.196612

# Taylor polynomials of e^x at 0, evaluated at 1: the error lies between 1/(n+1)! and e/(n+1)!
T = 1.0
for n in range(1, 5):
    T += 1 / math.factorial(n)
    print(n, round(T, 5), round(math.e - T, 5), round(1 / math.factorial(n + 1), 5), round(math.e / math.factorial(n + 1), 5))
# 1 2.0 0.71828 0.5 1.35914 | 2 2.5 0.21828 0.16667 0.45305 | 3 2.66667 0.05162 0.04167 0.11326 | 4 2.70833 0.00995 0.00833 0.02265

# log(1 + x): one digit per order at x = 0.1, divergence at x = 1.8
for x in (0.1, 1.8):
    T = 0.0
    for n in range(1, 5):
        T += (-1) ** (n + 1) * x ** n / n
        print(x, n, f'{T:.6f}', f'{math.log1p(x) - T:.2e}', f'{x ** (n + 1) / (n + 1):.1e}')
# 0.1: errors -4.69e-03 3.10e-04 -2.32e-05 1.85e-06, bounds 5.0e-03 3.3e-04 2.5e-05 2.0e-06
# 1.8: T_n = 1.800000 0.180000 2.124000 -0.500400, log(2.8) = 1.029619

# log(1 + x) for tiny x: forming 1 + x first loses digits, log1p does not
x = 1e-10
print(f'{(math.log(1 + x) - math.log1p(x)) / math.log1p(x):.1e}')   # 8.3e-08

# gradient descent (step 0.2) against Newton on f(x) = e^x - 2x, minimum at log 2
xg = xn = 0.0
for k in range(5):
    print(k, f'{xg - math.log(2):.3f}', f'{xn - math.log(2):.1e}')
    xg -= 0.2 * (math.exp(xg) - 2)
    xn -= (math.exp(xn) - 2) / math.exp(xn)
# errors: GD -0.693 -0.493 -0.337 -0.223 -0.143; Newton -6.9e-01 3.1e-01 4.3e-02 9.0e-04 4.0e-07

# finite differences of e^x at 1: predicted optimal steps and errors, then measured errors
u = 2.0 ** -53
print(f'{2 * math.sqrt(u):.1e} {2 * math.e * math.sqrt(u):.1e} {(3 * u) ** (1 / 3):.1e} {math.e / 2 * (3 * u) ** (2 / 3):.1e}')
# 2.1e-08 5.7e-08 6.9e-06 6.5e-11
for k in (3, 5, 6, 8, 12):
    h = 10.0 ** -k
    fwd = (math.exp(1 + h) - math.exp(1)) / h
    cen = (math.exp(1 + h) - math.exp(1 - h)) / (2 * h)
    print(k, f'{abs(fwd - math.e):.1e} {abs(cen - math.e):.1e}')
# 3 1.4e-03 4.5e-07 | 5 1.4e-05 5.9e-11 | 6 1.4e-06 1.6e-10 | 8 6.6e-09 6.6e-09 | 12 4.3e-04 2.1e-04

# where it breaks: a central difference across the kink of |x|, and a function whose Taylor series is 0
for h in (1e-5, 1e-7):
    print(h, round((abs(1e-6 + h) - abs(1e-6 - h)) / (2 * h), 6))
print(round(math.exp(-1 / 0.5 ** 2), 4))
# 1e-05 0.1 | 1e-07 1.0
# 0.0183

Next#

One variable is the exception in machine learning: a loss depends on a whole vector of weights, and a layer maps a vector to a vector. The next note turns the derivative into the gradient, the best linear approximation of a function of many variables, shows that it points uphill most steeply and across the level sets, replaces the chain rule by a product of Jacobian matrices, and turns the second derivative into the Hessian, whose eigenvalues classify the critical points.

References#

  • D. Merkulov. Optimization for ML, lecture course, HSE University, 2024. Course page; lecture 2 (line search and the first-order Taylor model of the step, the sufficient-decrease condition, differentials).
  • J. Nocedal, S. J. Wright. Numerical Optimization, 2nd ed. Springer, 2006. The chapter on calculating derivatives: finite-difference approximations and the choice of the step.
  • N. J. Higham. Accuracy and Stability of Numerical Algorithms, 2nd ed. SIAM, 2002. The chapter on floating point: the model of arithmetic and the unit roundoff.
  • G. Strang, E. Herman. Calculus Volume 1. OpenStax, 2016 (2016a). Theorems 2.11 (intermediate value), 3.3, 3.8, 3.14 and 3.15 (derivatives of powers, sine, the exponential and the logarithm), 4.1 (extreme value), 4.2 (Fermat), 4.4 (Rolle) and 4.5 (mean value).
  • G. Strang, E. Herman. Calculus Volume 2. OpenStax, 2016 (2016b). Theorem 6.7 (Taylor’s theorem with remainder, proved by Rolle’s theorem).