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 , 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 . The true value is . The guess is off by , 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 and is the difference quotient . For at it is : for and for . The derivative is its limit as , here .
The limit hides what the derivative is for, which is replacing a curve by a line. Rewritten, the definition says that is differentiable at when, near , it equals a linear function of the increment plus an error that is small compared with the increment:
The two definitions agree, because dividing the error by gives
which tends to 0 exactly when the difference quotient tends to . A quantity is written when, divided by , it tends to 0, and when it is at most a constant times for small . So .
The tangent is the best line through . Any other slope leaves the error , which divided by tends to . Another line misses by an amount proportional to ; the tangent misses by less than any multiple of .
Example. For at 4, :
| step | tangent | error | ||
|---|---|---|---|---|
The error falls like , and to leading order it is , the last column. Taylor’s theorem below explains why.
The rules, and the chain rule derived#
Four derivatives come straight from the definition. For the binomial expansion gives . The number is defined as the base for which , so . For , the addition formula and the limits , give . And follows by differentiating 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, , holds because the linear parts of and add. The product rule, , comes from multiplying the two approximations: , since every other product contains , or and is . The third, for a composition, is the chain rule:
It composes the two linear approximations. A step in moves by about , and that step moves by about times it. To make this exact, write and , the step that causes in the input of . Differentiability of at can be written as with as and ; this form allows , which can happen for . Then
In the limit by differentiability of , and , so . The quotient rule follows from the product rule and the chain rule applied to .
Example: the sigmoid. is with the inner function and the outer , whose derivatives are and . So
At , and ; a central difference with 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 at a point . Matching the second, third, up to the -th derivative as well gives a polynomial that hugs more closely. The Taylor polynomial of order at is
where is the -th derivative. It is the only polynomial of degree at most whose first derivatives at equal those of : the -th derivative of at is 1 when and 0 otherwise, so each coefficient is forced. is the tangent.
How far is from ? Taylor’s theorem answers with the next derivative. If has continuous derivatives on an interval containing and , then for some between and
This is the remainder in Lagrange form. The theorem holds under weaker assumptions too: a proof by Rolle’s theorem needs only that exist (Strang and Herman, 2016b, theorem 6.7). With derivatives at alone, one still gets the Peano form , 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 , 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, , is Rolle applied to minus its chord (theorem 4.5).
Lagrange. Fix and choose with for . Since matches the first derivatives, . Rolle on gives , Rolle on gives , and so on up to . So , and is the Lagrange form.
Peano. Here has . By induction on , such an is ; for this is the definition of . For the step, satisfies the claim for . Given , the mean value theorem gives, for close enough to and some between and , .
We prove the theorem through an exact formula for the remainder,
by induction on . For it is the fundamental theorem of calculus, . Assume it for and integrate by parts, differentiating and integrating , whose antiderivative in is :
The bracket vanishes at , and its value at is the next term of the Taylor polynomial. So , which completes the induction.
The Lagrange form follows from the integral. The weight keeps one sign for between and . So the integral lies between and times , where and are the minimum and maximum of the continuous on the interval. By the intermediate value theorem, takes the value in between at some point (Strang and Herman, 2016a, theorems 4.1 and 2.11):
As the remainder is : each extra order buys one more power of the distance.
Example: . All derivatives of are , so at the polynomial is , and the remainder at is with . The theorem traps the error between and :
| error | ||||
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
The factorial grows faster than any power, so for the remainder goes to 0 at every . Indeed , and once , each further factor of is below . So the Taylor series converges to everywhere.
Example: . The -th derivative is , so at the coefficients are and . For the Lagrange remainder is
because . At , where :
| error | bound | |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
Each order gains about one digit, a factor . At the same polynomials give , , and , swinging further from at every order. The terms grow when . A series whose terms do not tend to 0 diverges, and the bound grows with the terms. A Taylor polynomial is a local statement.
The tangent and Taylor polynomials of increasing order
Libraries use Taylor polynomials to evaluate functions near a point where the direct formula loses digits. For , rounding to a double moves it by up to , half the spacing of doubles near 1. Since and the slope of there is 1, the result inherits that error, up to relative; here it comes out as . Near 0 the series says , and the library function log1p computes it to full precision; expm1 does the same for .
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 decreases and how fast; the second-order term says for how long the decrease lasts. Take a gradient step with step size on a function whose second derivative is bounded, . Write and expand with Taylor’s theorem for and ; the bound on then turns the one unknown factor into a guarantee:
For the bracket is positive, and every step with lowers . 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 (Merkulov, 2024, lecture 2). The same bound, with 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 over , when , gives , and Newton’s step : a gradient step whose size is set by the curvature.
At a critical point, where , Taylor with reads . If , then near by continuity, and is a strict local minimum; if , a strict local maximum. If the test says nothing: , and all have at 0, and the first has no extremum there, the second a minimum and the third a maximum.
Example. has and , so its minimum is at , with . From the errors are:
| step | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| gradient descent, | |||||
| Newton |
Near the minimum, gradient descent multiplies the error by about per step. Subtracting from the update and applying the mean value theorem to , with , gives with between and . 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 is available only as a program, its derivative can be approximated by a difference quotient with a small fixed . Taylor’s theorem gives the error of the formula, and floating point adds a second error that grows as shrinks. The best balances the two.
Truncation error#
The forward difference comes from Taylor with , and the central difference from Taylor with at both and :
Subtracting the two expansions cancels and the terms. The average of and is a value of the continuous between them, by the intermediate value theorem:
The same steps with give . 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 (floating point; Higham, 2002). Assume each computed value of is correctly rounded, as math.exp nearly is. Then and each carry an error of at most about , so the numerator of a difference quotient is wrong by up to about , and dividing by a small 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 a bound on near , the total errors are at most
The best step#
In each bound one term grows with and the other falls. The second derivative of each bound in is positive for , so the bound is convex there, and it is smallest where its derivative in vanishes. For the forward difference write , with and :
For the central one write , with and . At the optimum , which gives the last line:
When and its derivatives are of order 1, the forward difference is best at and keeps about half of the sixteen digits. The central difference is best at and keeps about two thirds (Nocedal and Wright, 2006).
Example. at , where . The forward difference has and a best error bound of . The central difference has and a bound of . Measured in double precision:
| step | forward error | central error |
|---|---|---|
Both errors fall until rounding takes over and then rise again, the central one from a lower floor and a larger step.
The error of a finite difference against the step
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 , so that the computed equals the we divide by; a power of two such as guarantees it for , since is a double. And a finite-difference gradient of a function of variables costs or 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 , the shape of a ReLU’s kink, at , where exactly. A central difference with straddles the kink:
The answer is wrong by 90%, and no rounding is involved: the Taylor expansion behind the formula does not exist across the kink. With , 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 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 , extended by 0 at 0, has every derivative equal to 0 at 0, so every is identically 0.
Proof: every derivative of e^(−1/x²) vanishes at 0
For , induction with the product and chain rules gives for a polynomial . At 0, by the definition of the derivative and ,
because with every term is a power times , and : the series of gives for any integer .
Its series converges everywhere, to the wrong function: at the function is . The remainder formula is still correct; its bound needs 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#
- : the derivative is the slope of the best linear approximation.
- The chain rule composes linear approximations; backpropagation applies it node by node.
- Taylor: ; each order adds a power of , and a series can still diverge far from .
- With , a gradient step with always decreases ; Newton’s step uses the curvature.
- Forward differences have error , central , rounding adds ; the best steps are about and .
- A difference across a kink is wrong however small the rounding error.
Code#
The worked examples: the tangent of , the chain rule for the sigmoid, the Taylor errors of and , 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).