Skip to content
AI.info

Mathematical foundations

Derivatives and Local Linearization

Build derivative intuition from rates, slopes, perturbations, Taylor approximations, and the limits of local reasoning.

By the end you can

The derivative answers a counterfactual nearby question

The derivative f′(x) of a scalar function f(x) describes how the output would change under an infinitesimal change in x. It is a local sensitivity, not a global summary. The linear approximation f(x + Δ) ≈ f(x) + f′(x)Δ turns that sensitivity into a nearby prediction. It improves as Δ becomes small enough for curvature to matter less. ML uses the idea to update parameters, analyze feature sensitivity, and propagate influence through composed functions.

What follows treats that approximation as something with measured consequences rather than a formality. What one linear step can do to a trained classifier. What a gradient costs to compute by each available method. And where the arithmetic of the machine stops the mathematics of the limit.

A derivative is the best local linear explanation of how a function changes.

Taylor expansion turns derivatives into a local model

The first-order Taylor model uses slope: f(x+Δ) ≈ f(x)+f′(x)Δ. The second-order model adds curvature: ½f″(x)Δ². A small derivative does not always mean little change. If curvature is large or Δ is not small, the second-order term can dominate. Optimization methods differ partly in which local model they trust. Gradient descent uses first-order information; Newton-style reasoning uses curvature.

How much a first-order model buys is measurable, and it was measured on the input rather than on the parameters. In 2015 Goodfellow and two colleagues built a perturbation out of nothing but the linear term: “We can linearize the cost function around the current value of θ, obtaining an optimal max-norm constrained pertubation”. One step in the sign of that gradient, at epsilon = 0.25, drove a shallow softmax classifier to a 99.9% error rate on the MNIST test set, with 79.3% average confidence in its wrong answers. At epsilon = 0.1 the same construction produced an 87.15% error rate on CIFAR-10, with 96.6% average probability on the wrong labels.

NIST catalogues the technique in exactly those terms: “Goodfellow et al. [144] introduced an efficient method for generating adversarial examples for deep learning: the Fast Gradient Sign Method (FGSM), which performs a single iteration of gradient descent for solving the optimization.”

Read the numbers as a statement about the local model and not only about security. The linearization is valid in a neighborhood. The attack works because it stays inside one and spends its whole budget on the slope.

Key idea

Smaller finite-difference steps are not always better

A large step introduces truncation error, because the function is curved across the interval. An extremely small step can lose precision, because nearly equal floating-point values are subtracted. A 2018 survey of automatic differentiation, by Baydin and colleagues, puts the second half of that as a rule broken twice over: “Using the limit definition of the derivative for finite difference approximation commits both cardinal sins of numerical analysis: "thou shalt not add small numbers to big numbers", and "thou shalt not subtract numbers which are approximately equal".”

The balance is not a caution. It is a plotted curve. The same survey plots forward- and centre-difference error against h over 10^-17 to 10^-3, labels the two halves “Round-off error dominant” and “Truncation error dominant”, and shows the total error bottoming out between them. An independent group states the same crossover: “Hence, a tradeoff between truncation errors and roundoff exists.”

Central differences move the truncation term from first order to second order in h. That is why they are usually the better diagnostic. They are bought with evaluations: a Jacobian of f: R^n -> R^m by central differences costs 2mn function evaluations. So gradient checks should test several step sizes and compare relative error, especially near zero gradients or nondifferentiable points.

Finite-difference accuracy balances local approximation error against floating-point cancellation.

Case

Why SciPy’s default finite-difference step is about 1.49e-8

The constants here are fixed by the number format, not by the function under test. In IEEE 754 binary64 the machine epsilon is 2⁻⁵², about 2.22e-16. The NumPy reference page for numpy.finfo states it for 64-bit binary floats as “eps = 2**-52, approximately 2.22e-16”. An unrelated host prints the same constant to full precision: the Julia Base documentation for eps shows “julia> eps() 2.220446049250313e-16”.

Balancing truncation against cancellation puts the best forward-difference step near the square root of that number. FiniteDiff.jl's step-size documentation derives the steps by minimizing truncation plus round-off, and records the result as “Forward differences : h* = sqrt(eps)”, with eps^(1/3) for central differences. SciPy's approx_fprime defaults to exactly that. Its epsilon parameter “Defaults to sqrt(np.finfo(float).eps), which is approximately 1.49e-08.”, and the published signature shows epsilon = np.float64(1.4901161193847656e-08).

On a logarithmic ruler the arrangement is visible at a glance: 1 at the top, 2.22e-16 at the bottom, and 1.49e-8 sitting at the geometric mean of the two. In bits, an epsilon of 2⁻⁵² and a step of 2⁻²⁶. Nothing about f entered that derivation.

Figure

Why the default finite-difference step is 1.49e-8: it is the square root of the machine epsilon, sitting exactly halfway between 1 and 2.22e-16 in log space.

Visual

From secant slope to tangent slope

Finite changes reveal average behavior. The derivative emerges as the interval shrinks. The four steps are the definition. They are also an instruction no machine can carry out to its end, which is the subject of the callout above and of the closing section below.

FigureProcess · 4 steps
  1. 1. Choose two points

    Compute the output difference over a finite interval.

  2. 2. Form a secant slope

    Divide Δf by Δx to obtain an average rate.

  3. 3. Shrink the interval

    Move the second point toward the first.

  4. 4. Take the limit

    If the slopes converge, their limit is the derivative.

The derivative is not a small finite difference; it is the limiting local rate that finite differences approximate.

Comparison

Analytic, automatic, and numerical differentiation

All three estimate derivatives. They rely on different mechanisms, and they do not cost the same. Baydin and colleagues quantify the gap in their 2018 survey: “The O(n) complexity of numerical differentiation for a gradient in n dimensions is the main obstacle to its usefulness in machine learning, where n can be as large as millions or billions in state-of-the-art deep learning models”. Reverse-mode automatic differentiation instead returns the whole gradient of a scalar function in a single pass. Its operation count is bounded by a constant factor c that is guaranteed to be c < 6 and is typically in the range 2 to 3.

The same contrast appears in an independent 2019 review by Margossian. Finite differentiation “requires at least D evaluations, where D is the number of partial derivatives required”, while AD is “Exact, speed is comparable to hand-coding derivatives”. That is the whole argument for the middle column at scale: n evaluations against one pass at under six times the cost of evaluating f.

FigureComparison · 3 columns

Analytic differentiation

Derive a symbolic formula using calculus rules.

  • Can reveal structure and simplifications
  • Easy to make algebraic mistakes in large models
  • Produces an exact expression under the stated function
  • Useful for teaching and small components

Automatic differentiation

Apply chain-rule operations to a computer program.

  • Evaluates derivatives to machine precision
  • Scales to large computational graphs
  • Is neither symbolic simplification nor finite difference
  • Requires differentiable program paths

Finite differences

Approximate slopes from nearby function evaluations.

  • Simple and broadly applicable
  • Useful for gradient checks
  • Suffers truncation and rounding tradeoffs
  • Expensive in many dimensions

Analogy

The road’s current slope predicts the next few meters

A cyclist uses the slope under the wheels to estimate elevation a few meters ahead. That is a first-order local model. Curvature describes how quickly the road’s slope changes. On a gentle bend the estimate works; near a sharp crest it fails rapidly.

At a cliff or a corner no single tangent describes the change at all. Differentiability is an assumption about local regularity.

Local sensitivity is useful only within the neighborhood where the local model remains credible.

Steps

A trustworthy derivative check

Use numerical checks as diagnostics, not as the primary training method. And read the sweep over h for what it is: a measurement of the differencing scheme rather than of the derivative. There is a published way to see the difference.

The complex-step approximation was introduced in 1998 by Squire and Trapp, whose abstract reads: “A method to approximate derivatives of real functions using complex variables which avoids the subtractive cancellation errors inherent in the classical derivative approximations is described.” Martins and two colleagues generalised it in 2003, reporting that “The complex-step method is tested in two large multidisciplinary solvers and the resulting sensitivities are compared to results given by finite differences. The resulting sensitivities are shown to be as accurate as the analyses.”

A third group states the property independently: “the Jacobian approximation is not subject to subtractive cancellations inherent in roundoff errors”, and “since an arbitrarily small step-size can be chosen, the complex-step method can achieve near analytical accuracy”.

If a different way of forming the estimate removes the cancellation term altogether, then the floor your sweep runs into is a property of subtraction, not of differentiation. That is why the five steps below vary h and compare relative error instead of trusting any single value.

FigureProcess · 5 steps
  1. 1. Isolate a small function

    Reduce the graph to a component with deterministic behavior.

  2. 2. Pick representative coordinates

    Check several parameters, including different scales.

  3. 3. Use central differences

    Compare f(x+h) and f(x−h) across a range of h.

  4. 4. Compare relative error

    Scale the discrepancy by derivative magnitude and numerical tolerance.

  5. 5. Investigate nonsmooth points

    Repeat away from kinks, clipping thresholds, and discrete branches.

Example

A local approximation for logistic probability

Let p(z)=1/(1+e⁻ᶻ). At z=0, p=0.5 and p′=0.25.

  • Small increase: For Δ=0.1, the linear estimate is 0.5 + 0.25×0.1 = 0.525.
  • Actual value: p(0.1) is about 0.525, so the local model is accurate here.
  • Saturation: At large positive or negative z, p′ becomes small and the function responds weakly. That is observable during training, not only on the curve. It was measured in 2010. Glorot and Bengio report of a randomly initialised sigmoid network that “The top hidden layer quickly saturates at 0 (slowing down all learning), but then slowly desaturates around epoch 100.” Their depth-five model never escaped the regime at all.
  • Interpretation: A small derivative in saturation is a property of the function, not evidence that the input is unimportant globally. It can still be evidence about the architecture: “We find that the logistic sigmoid activation is unsuited for deep networks with random initialization because of its mean value, which can drive especially the top hidden layer into saturation.”
  • Model relevance: The cost of weak gradients is measured in training time. A four-layer convolutional network with ReLUs reached 25% training error on CIFAR-10 six times faster than the same network with tanh units. Krizhevsky and colleagues measured that in 2012: “In terms of training time with gradient descent, these saturating nonlinearities are much slower than the non-saturating nonlinearity f(x) = max(0,x).”

Position

The step in a derivative check is set by the format and the method, not chosen by taste

Calculus defines the derivative as a limit. Shrink the interval, take the slopes, and if they converge, their limit is the derivative. Read as advice about computation, that says smaller is better, without end. A machine cannot follow it. Two errors move in opposite directions as the step shrinks. A large step carries truncation error, because the function curves across the interval. A very small one subtracts two nearly equal floating-point values and loses the difference to rounding. Somewhere between them the total stops falling. That is the bottom of the curve Baydin and colleagues plot over h from 10^-17 to 10^-3, between the regimes they label “Round-off error dominant” and “Truncation error dominant”. Where it stops is not a matter of taste, and it is not a property of the function alone. In IEEE 754 binary64 the machine epsilon is 2⁻⁵², about 2.22e-16. Balancing truncation against cancellation puts the best forward-difference step near its square root. That is why the default in SciPy’s approx_fprime is about 1.49e-8.

The format is not folklore, and it is worth being able to point at the document. It is IEEE Std 754-2019, the IEEE Standard for Floating-Point Arithmetic. The IEEE Standards Association approved it on 13 June 2019, and it was published on 22 July 2019. Its scope reads: “This standard specifies interchange and arithmetic formats and methods for binary and decimal floating-point arithmetic in computer programming environments.” The International Electrotechnical Commission published the international adoption on 8 May 2020, as ISO/IEC 60559:2020, edition 2.0, replacing ISO/IEC/IEEE 60559:2011: “ISO/IEC 60559:2020(E) specifies formats and methods for floating-point arithmetic in computer systems - standard and extended functions with single, double, extended, and extendable precision - and recommends formats for data interchange.” Nowhere in that chain — standard, format, epsilon, square root, default — does the function under test appear. Another format, or a central difference in place of a forward one, gives different constants. That is why this lesson still asks for several step sizes and a comparison of relative error, rather than trust in one value, especially near zero gradients and near kinks.

Treating this as mathematics rather than as a footnote about the code is what keeps two failures apart. Automatic differentiation applies chain-rule operations to the executed program, up to floating-point error. It never forms the difference of two nearly equal values of f, so it does not pay the cancellation penalty that differencing pays. The complex-step approximation of Squire and Trapp escapes the same penalty by the same route, without subtracting nearly equal values at all. A check run at a step far below that best step may well be reporting on the subtraction rather than on the gradient. Finite precision is not the point where the mathematics stops and the engineering starts. It is a second set of terms in the same error budget.

In binary64 a forward difference stops improving near the square root of machine epsilon, and that constant comes from IEEE Std 754-2019 and the chosen method, not from the function alone.

Key takeaways