Module contents
Lesson 13 of 26Core 70 min

Numerical derivatives: finite differences, complex step and symbolic differentiation

Understand the limits of alternatives to automatic differentiation: finite differences trade truncation against rounding, complex step avoids cancellation for analytic functions, and symbolic expressions can grow uncontrollably. Build a gradient checker for later AD engines.

After this lesson you can

  • Derive forward, central and higher-order finite-difference errors using Taylor expansions.
  • Calculate the optimal finite-difference step and explain the V-shaped error curve.
  • Implement complex-step derivatives and Richardson extrapolation for derivatives.
  • Build a robust gradient checker based on relative error.
  • Explain symbolic expression growth and its relation to sharing subexpressions.

Before you start

Motivation: an incorrectly programmed gradient raises no error

You write a new model layer with a manual backward pass because the automatic version uses too much memory. A detail goes wrong: you forget the regularization term λW\lambda\mat{W}, the 2 in the derivative of a square, or a sign in a bias component. No exception appears. Loss falls (gradient descent tolerates directions merely resembling the right one), the model trains somewhat worse, and nobody knows why. Backpropagation turns a calculation error into silent degradation.

Compare the gradient computed by your code against an independent estimate obtained only by evaluating the function. Before automatic differentiation, there were three ways to compute derivatives, each studied here because it fails instructively:

  • Finite differences. Evaluate ff at nearby points and subtract. Easy to program in one line, but accuracy is limited by the truncation–rounding trade-off: with optimal step, about half the digits of ff remain.
  • Complex step. For analytic functions, evaluating ff at x+ihx + ih yields the derivative without subtraction and therefore with all digits. In exchange, code for ff must genuinely accept complex numbers, which many common functions do not.
  • Symbolic differentiation. Apply derivative rules to the expression. It is exact, but without sharing repeated subexpressions, derivative formulas grow exponentially with composition depth.

Finally, build a gradient checker for the automatic differentiation engines of the next three lessons and any later layer, and see four traps that make it useless: the wrong step, single precision, kinks and absolute error.

Finite differences and truncation error

The derivative is a limit, f′(x)=lim⁡h→0(f(x+h)−f(x))/hf'(x) = \lim_{h \to 0} (f(x + h) - f(x))/h. Finite differences truncate that limit at a small but nonzero hh.

The error from truncating the limit in exact arithmetic is truncation error, given by the Taylor remainder.

Proof
  1. Taylor with Lagrange remainder: f(x+h)=f(x)+hf′(x)+h22f′′(ξ)f(x + h) = f(x) + hf'(x) + \tfrac{h^2}{2}f''(\xi) with ξ∈(x,x+h)\xi \in (x, x + h). Subtract f(x)f(x) and divide by hh.
  2. Expand through order 3 with a remainder on each side: f(x±h)=f(x)±hf′(x)+h22f′′(x)±h36f′′′(ξ±)f(x \pm h) = f(x) \pm hf'(x) + \tfrac{h^2}{2}f''(x) \pm \tfrac{h^3}{6}f'''(\xi_\pm), with ξ+∈(x,x+h)\xi_+ \in (x, x + h) and ξ−∈(x−h,x)\xi_- \in (x - h, x). Subtraction cancels f(x)f(x) and the f′′f'' term:
f(x+h)−f(x−h)2h=f′(x)+h26⋅f′′′(ξ+)+f′′′(ξ−)2.\frac{f(x + h) - f(x - h)}{2h} = f'(x) + \frac{h^2}{6}\cdot\frac{f'''(\xi_+) + f'''(\xi_-)}{2}.

The average of f′′′(ξ+)f'''(\xi_+) and f′′′(ξ−)f'''(\xi_-) lies between them; since f′′′f''' is continuous on [ξ−,ξ+][\xi_-, \xi_+], the intermediate value theorem gives an ξ\xi in that interval where f′′′f''' equals the average.

∎

Symmetry gives an extra order: in the central difference, even Taylor terms have the same sign in f(x+h)f(x + h) and f(x−h)f(x - h) and cancel upon subtraction. For the same reason, the full expansion of D0D_0 has only even powers of hh,

D0f(x)=f′(x)+h26f′′′(x)+h4120f(5)(x)+h65040f(7)(x)+⋯ ,D_0 f(x) = f'(x) + \frac{h^2}{6}f'''(x) + \frac{h^4}{120}f^{(5)}(x) + \frac{h^6}{5040}f^{(7)}(x) + \cdots,

a fact exploited by Richardson extrapolation below.

More nodes, higher order: the Taylor table

Where do higher-order formulas come from, such as the five-point central formula

f′(x)≈−f(x+2h)+8f(x+h)−8f(x−h)+f(x−2h)12h,error=−h430f(5)(x)+O(h6)?f'(x) \approx \frac{-f(x + 2h) + 8f(x + h) - 8f(x - h) + f(x - 2h)}{12h}, \qquad \text{error} = -\frac{h^4}{30}f^{(5)}(x) + \bigO(h^6)?

Taylor-expand each f(x+sjh)f(x + s_j h) and group by derivative:

1hm∑j=1nwjf(x+sjh)=∑k≥0(∑j=1nwjsjkk!)⏟μkhk−mf(k)(x).\frac{1}{h^m}\sum_{j=1}^n w_j f(x + s_j h) = \sum_{k \ge 0} \underbrace{\Big(\sum_{j=1}^n w_j \frac{s_j^k}{k!}\Big)}_{\mu_k} h^{k - m} f^{(k)}(x).

For the right side to equal f(m)(x)f^{(m)}(x) plus small error, the “moments” μk\mu_k must equal μm=1\mu_m = 1 and μk=0\mu_k = 0 for other controllable kk. With nn nodes there are nn unknowns, so impose μk=δkm\mu_k = \delta_{km} for k=0,…,n−1k = 0, \dots, n - 1:

∑j=1nwjsjkk!=δkm,k=0,1,…,n−1.\sum_{j=1}^n w_j \frac{s_j^k}{k!} = \delta_{km}, \qquad k = 0, 1, \dots, n - 1.

This is a Vandermonde system (each row is a power of the nodes divided by k!k!), invertible for distinct nodes. This Taylor table produces all finite-difference formulas.

The proof repeats the calculation with Lagrange remainder of order q+1q + 1 at each node. With symmetric nodes and odd mm, weights are antisymmetric and μk\mu_k vanishes for every even kk. If nn is even, the first candidate q=nq = n is even and vanishes, gaining an order: two-node stencil {−1,1}\{-1, 1\} has order 2 rather than 1. If nn is odd, the center receives weight 0 (its contribution to each μk\mu_k with k≥1k \ge 1 is zero and antisymmetry forces it), contributing nothing: the three-node central stencil {−1,0,1}\{-1, 0, 1\} is the two-node one with an unused node, and its order 2 is the generic n−mn - m.

Solving the Vandermonde system works for four or five nodes, but is ill-conditioned and requires a different system per derivative. Fornberg (1988) gave a recursive algorithm computing weights for all derivatives 0,…,M0, \dots, M on arbitrary nodes at once, adding nodes one by one without forming a matrix. PDE libraries use it to build stencils on irregular grids, and you will implement it in the lab.

InteractiveDifference formula builder
f(1)(x)≈1h[−12 f(x−h)+0 f(x)+12 f(x+h)]f^{(1)}(x) \approx \frac{1}{h}\Big[-\tfrac{1}{2}\,f(x-h) + 0\,f(x) + \tfrac{1}{2}\,f(x+h)\Big]
error≈16 h2 f(3)(x)\text{error} \approx \tfrac{1}{6}\,h^{2}\,f^{(3)}(x)
measured error of f′(0.6), f = e^(sin x)truncation + rounding model
10⁻¹⁵10⁻¹²10⁻⁹10⁻⁶10⁻³110⁻⁸10⁻⁷10⁻⁶10⁻⁵10⁻⁴10⁻³10⁻²10⁻¹1step hrelative error
Derivative
Nodes3
Accuracy order pp2
Error constant CC1/6
Rounding amplification ∑j∣wj∣\sum_j \abs{w_j}1
Optimal step (model)5.9·10⁻⁶
Minimum error (model)3.4·10⁻¹¹
Best measured h…
Best measured error…
Drag nodes (in units of hh) and choose the derivative. Weights come from Fornberg's algorithm; order pp and constant CC from the first nonzero moment μq\mu_q. Below is actual formula error on g(x)=esin⁡xg(x) = e^{\sin x} at x0=0.6x_0 = 0.6, computed in float64, with a dashed truncation-plus-rounding model. Start with three symmetric nodes: why does the center weigh 0? Move an endpoint and watch order fall; try the three-node one-sided formula (same order as central, but what constant?) and a third derivative, whose rounding floor rises like h−3h^{-3}.

Three observations from the figure:

  1. Order is not determined by node count alone. One-sided (−3f(x)+4f(x+h)−f(x+2h))/(2h)(-3f(x) + 4f(x + h) - f(x + 2h))/(2h) and three-node central stencils are order 2, but the one’s constant is −13-\tfrac13 versus 16\tfrac16: twice the error at the same hh. Irregular {−1,0,12,2}\{-1, 0, \tfrac12, 2\} is order 3 with four nodes, as n−mn - m predicts.
  2. Higher order amplifies rounding. Sum ∑j∣wj∣\sum_j \abs{w_j} measures amplification of error in each evaluation of ff. It is 1 for two-node central, 1.5 for five-node and 4 for the three-node second derivative (f(x+h)−2f(x)+f(x−h))/h2(f(x + h) - 2f(x) + f(x - h))/h^2.
  3. Higher derivatives are worse. Rounding error in a formula for f(m)f^{(m)} scales as u/hmu/h^m: higher derivatives raise the floor earlier and preserve fewer digits. That is the next section’s topic.

Truncation plus rounding: the V-shaped curve

The theorem suggests taking hh extremely small. Computers show the opposite. Compute D+D_+ for f(x)=exf(x) = e^x at x=1x = 1 with h=10−15h = 10^{-15}: relative error is 14%, as the lab cell prints. Subtraction fails. f(x+h)f(x + h) and f(x)f(x) agree in nearly all digits, each carrying rounding error of size u∣f∣u\abs{f}; subtraction cancels shared digits, leaving noise divided by tiny hh. This is catastrophic cancellation caused by the method itself.

To quantify this, suppose the program evaluating ff returns f^(y)=f(y)(1+δy)\hat f(y) = f(y)(1 + \delta_y) with ∣δy∣≤εf\abs{\delta_y} \le \eps_f. If ff is a correctly rounded elementary operation, εf=u\eps_f = u, the unit roundoff; for a long program, εf\eps_f may be much larger. Let M0≈∣f∣M_0 \approx \abs{f} and M2≥∣f′′∣M_2 \ge \abs{f''} near xx. Then

∣D^+f(x)−f′(x)∣≤M2h2⏟truncamiento+2εfM0h⏟redondeo=:E(h).\abs{\hat D_+ f(x) - f'(x)} \le \underbrace{\frac{M_2 h}{2}}_{\text{truncamiento}} + \underbrace{\frac{2\eps_f M_0}{h}}_{\text{redondeo}} =: E(h).

The first term is the preceding theorem; the second is subtraction error f^(x+h)−f^(x)\hat f(x + h) - \hat f(x) (at most εf∣f(x+h)∣+εf∣f(x)∣≈2εfM0\eps_f\abs{f(x + h)} + \eps_f\abs{f(x)} \approx 2\eps_f M_0) divided by hh. Floating-point subtraction and division add relative errors of size uu, negligible by comparison. This is the familiar forward error bound viewed differently: differentiation is ill-conditioned because relative input perturbation εf\eps_f produces output change 2εfM0/h2\eps_f M_0/h, larger as hh shrinks.

With M0≈M2≈1M_0 \approx M_2 \approx 1 and εf=u=2−53\eps_f = u = 2^{-53}, h∗=2u≈2.1×10−8h_\ast = 2\sqrt u \approx 2.1\times 10^{-8} and error is also ≈2.1×10−8\approx 2.1\times 10^{-8}: about 8 of the 16 digits of ff survive. The rule of thumb is therefore h≈ε≈1.5×10−8h \approx \sqrt{\eps} \approx 1.5\times 10^{-8}, of the same order and the default for scipy.optimize.approx_fprime. The formula’s h∗∝εfh_\ast \propto \sqrt{\eps_f} dependence matters, not the factor 2.

For central differences, truncation is M3h2/6M_3h^2/6 and rounding 2εfM0/(2h)=εfM0/h2\eps_f M_0/(2h) = \eps_f M_0/h:

E(h)=M3h26+εfM0h,h∗=(3εfM0M3)1/3,E(h∗)=(3εfM0)2/3M31/32.E(h) = \frac{M_3 h^2}{6} + \frac{\eps_f M_0}{h}, \qquad h_\ast = \Big(\frac{3\eps_f M_0}{M_3}\Big)^{1/3}, \qquad E(h_\ast) = \frac{(3\eps_f M_0)^{2/3}M_3^{1/3}}{2}.

With all quantities of order 1 and εf=u\eps_f = u, h∗≈6.9×10−6h_\ast \approx 6.9\times 10^{-6} and E≈2.4×10−11E \approx 2.4\times 10^{-11}: about two-thirds of the digits. Fourth order, with truncation M5h4/30M_5h^4/30 and amplification 18/12=1.518/12 = 1.5, has h∗=(45u/4)1/5≈1.0×10−3h_\ast = (45u/4)^{1/5} \approx 1.0\times 10^{-3} and E≈2×10−13E \approx 2\times 10^{-13}. Generally, an order-pp formula for the mm-th derivative has E(h)≈Ahp+Bu/hmE(h) \approx A h^p + B u/h^m, minimized at h∗∝u1/(p+m)h_\ast \propto u^{1/(p + m)} with error ∝up/(p+m)\propto u^{p/(p + m)}. No difference formula reaches uu: higher order moves the exponent toward 1 but never reaches it.

InteractiveThe V-shaped curve
f(x)=ex, x0=1f(x) = e^x,\ x_0 = 1
ForwardCentralFourth orderComplex step
10⁻¹⁶10⁻¹⁴10⁻¹²10⁻¹⁰10⁻⁸10⁻⁶10⁻⁴10⁻²110⁻²⁰10⁻¹⁸10⁻¹⁶10⁻¹⁴10⁻¹²10⁻¹⁰10⁻⁸10⁻⁶10⁻⁴10⁻²step hrelative error of f′(x₀)u = 2⁻⁵³
Exactly zero errors are plotted at the graph floor, 10⁻¹⁷.
MethodError at hDigitsBest hForward………Central………Fourth order………Complex step……≤ 10⁻⁸
10⁻¹¹
Relative error of f′(x0)f'(x_0) versus step hh on log–log axes, computed live in float64 (JavaScript numbers are binary64) and compared with the exact closed-form derivative. Slide hh or click the graph. Truncation dominates to the right of each V, with slope equal to order (1, 2, 4); rounding dominates to the left, with slope −1-1. Enable the model to see bound E(h)E(h) with εf=u\eps_f = u. Switch to 106+sin⁡x10^6 + \sin x: its derivative matches sin⁡x\sin x, but rounding scales with ∣f∣\abs{f} and every V's bottom rises. Complex step stays flat at uu down to h=10−20h = 10^{-20}.

The lab’s first cell reports, with exe^x at x=1x = 1: best forward hh is 10−810^{-8} with error 2.4×10−92.4\times 10^{-9}, central 5.0×10−65.0\times 10^{-6} with 8.5×10−138.5\times 10^{-13}, and fourth-order 3.5×10−43.5\times 10^{-4} with 4.5×10−144.5\times 10^{-14}. Steps match the model’s order of magnitude; measured errors are somewhat below the bound because the two evaluation rounding errors do not always combine in the worst direction. With 106+sin⁡x10^6 + \sin x, the forward V’s bottom rises to 6×10−66\times 10^{-6} and its best step shifts to 2.5×10−62.5\times 10^{-6}: M0=106M_0 = 10^6 enters rounding, not truncation. This occurs with a loss containing a large constant, such as enormous regularization or an unnormalized sum over millions of examples.

Richardson extrapolation for derivatives

The expansion of D0D_0 has only even powers of hh: D0(h)=f′+c2h2+c4h4+⋯D_0(h) = f' + c_2h^2 + c_4h^4 + \cdots. This is exactly the Richardson extrapolation setting from quadrature: combining D0(h)D_0(h) and D0(h/2)D_0(h/2) eliminates term h2h^2,

R(h)=4D0(h/2)−D0(h)3=f′(x)−h4480f(5)(x)+O(h6).R(h) = \frac{4D_0(h/2) - D_0(h)}{3} = f'(x) - \frac{h^4}{480}f^{(5)}(x) + \bigO(h^6).

Substitute the definition of D0D_0 and let k=h/2k = h/2: RR is exactly the five-point central formula with step kk. Richardson and the Taylor table reach the same result. Repeating, each level jj of table Ti,j=Ti,j−1+(Ti,j−1−Ti−1,j−1)/(4j−1)T_{i,j} = T_{i,j-1} + (T_{i,j-1} - T_{i-1,j-1})/(4^j - 1) removes another term, h2jh^{2j}. Ridders’ method (1982) organizes the table adaptively, stopping when estimated error stops falling.

The practical advantage over directly writing a high-order formula: Richardson starts with large steps where rounding u/hu/h is negligible, letting extrapolation remove truncation. In the cell, with h0=0.4h_0 = 0.4 and five reductions, the table reaches relative error 1.8×10−151.8\times 10^{-15}, much better than a difference with a single hh. Rounding does not vanish: each level amplifies it slightly, and starting at h0=10−4h_0 = 10^{-4} makes the diagonal drop to 3×10−133\times 10^{-13} at the first level then rise to 4×10−114\times 10^{-11}. Richardson still requires choosing an initial step.

Complex step: differentiation without subtraction

If ff is real and analytic at xx, evaluate it at a nearby complex point. Expand in the imaginary direction:

f(x+ih)=f(x)+ihf′(x)−h22f′′(x)−ih36f′′′(x)+h424f(4)(x)+⋯f(x + ih) = f(x) + ih f'(x) - \frac{h^2}{2}f''(x) - i\frac{h^3}{6}f'''(x) + \frac{h^4}{24}f^{(4)}(x) + \cdots

Since ff and its derivatives are real at xx, odd powers of ihih enter the imaginary part and even powers the real part. The derivative appears alone in the imaginary part, without subtraction.

Proof

Substitute z−x=ihz - x = ih into the series: f(x+ih)=∑kakikhkf(x + ih) = \sum_k a_k i^k h^k. Since aka_k and hh are real, the imaginary part receives only odd kk, k=2j+1k = 2j + 1, with Im⁡(i2j+1)=(−1)j\operatorname{Im}(i^{2j + 1}) = (-1)^j. With ak=f(k)(x)/k!a_k = f^{(k)}(x)/k!, dividing by hh yields the stated series, convergent because h<ρh < \rho.

∎

Truncation is the same size as central differences, h2f′′′/6h^2f'''/6. Rounding differs: without cancellation, if each complex operation has small relative error, result error is of order uu relative to f′f' for any hh. Choose hh small enough that h2∣f′′′∣/6h^2\abs{f'''}/6 is below u∣f′∣u\abs{f'}, for example h=10−20h = 10^{-20}, and the derivative retains all digits. In the cell, with Martins, Sturdza and Alonso’s (2003) test function f(x)=ex/sin⁡3x+cos⁡3xf(x) = e^x/\sqrt{\sin^3 x + \cos^3 x} at x=1.5x = 1.5, relative error is 2.2×10−162.2\times 10^{-16} (one relative ulp) with h=10−20h = 10^{-20} and 10−10010^{-100}, and 0 with h=10−8h = 10^{-8} and 10−30010^{-300}; with h=10−4h = 10^{-4}, truncation is visible: 1.3×10−81.3\times 10^{-8}.

The price is that all code for ff must be the real function’s holomorphic extension. This excludes:

  • Non-holomorphic functions. np.abs(z) returns modulus x2+h2\sqrt{x^2 + h^2}, which is real: the imaginary part is lost and the derivative is 0. The same applies to np.linalg.norm, np.vdot and product v.conj() @ v, which conjugate. np.sign(z) returns z/∣z∣z/\abs{z} and a false derivative. Rewrite using each branch’s analytic extension: ∣x∣\abs{x} is zz if Re⁡z≥0\operatorname{Re} z \ge 0 and −z-z otherwise.
  • Conversion to real. float(z) raises an error; astype(float) silently discards the imaginary part (with a warning few read).
  • Comparisons and branches. With Python scalars z > 0 raises an error; with NumPy arrays comparison is lexicographic and chooses by real part, correct except at ties. At a kink (∣x∣\abs{x} at 0, max at a tie) there is no derivative to compute.
  • Functions without complex versions. np.arctan2 and np.logaddexp do not accept complex inputs.

The lab cell tests each case. Also note that Re⁡f(x+ih)=f(x)−h22f′′(x)+⋯\operatorname{Re} f(x + ih) = f(x) - \tfrac{h^2}{2}f''(x) + \cdots gives the second derivative but subtracts f(x)f(x): cancellation returns, and with h=10−20h = 10^{-20} the cell obtains −1.8×1025-1.8\times 10^{25} instead of 9.469.46.

Complex step is closely related to the next lesson’s dual-number arithmetic: there evaluate f(x+ϵ)f(x + \epsilon) with ϵ2=0\epsilon^2 = 0 instead of i2=−1i^2 = -1, and the part accompanying ϵ\epsilon is exactly f′(x)f'(x), without truncation or hh. Complex step obtains nearly the same using the complex type available in most languages, at the cost of negligible truncation h2h^2.

Cost: nn or 2n2n evaluations per gradient

The above concerns one variable. For the gradient of f:Rn→Rf: \R^n \to \R, estimate each partial derivative separately by perturbing one coordinate at a time:

∂f∂θj(θ)≈f(θ+hej)−f(θ−hej)2h,j=1,…,n.\frac{\partial f}{\partial \theta_j}(\theta) \approx \frac{f(\theta + h\vb{e}_j) - f(\theta - h\vb{e}_j)}{2h}, \qquad j = 1, \dots, n.

Forward differences need n+1n + 1 evaluations of ff (reusing f(θ)f(\theta)), central 2n2n, and complex step nn complex evaluations. Cost grows linearly with parameter count, while neural-network nn ranges from millions to billions. Baydin et al. (2018) identify numerical differentiation’s O(n)\bigO(n) complexity for a gradient in nn dimensions as its main machine-learning obstacle. Reverse-mode automatic differentiation computes the whole gradient at a small fixed multiple of evaluating ff, independent of nn (the cheap gradient principle). Finite differences are thus unsuitable for training but useful for checking: not every component must be checked, and directional derivative ∇f(θ)⊤v≈(f(θ+hv)−f(θ−hv))/(2h)\grad f(\theta)\T\vb{v} \approx (f(\theta + h\vb{v}) - f(\theta - h\vb{v}))/(2h) costs two evaluations for any direction v\vb{v}.

Symbolic differentiation and expression growth

The third approach uses a computer algebra system: represent ff as an expression tree and apply differentiation rules. Symbolic differentiation returns another exact expression that can be simplified, printed or turned into code. sympy.diff(sp.exp(x) * sp.sin(x), x) gives exp(x)*sin(x) + exp(x)*cos(x) without hh or truncation error.

Composition causes trouble. Product rule (uv)′=u′v+uv′(uv)' = u'v + uv' copies uu and vv: if uu and vv are large expressions themselves, the derivative contains two copies of each plus their derivatives. Baydin et al. (2018, table 1) illustrate this with the logistic map l1=xl_1 = x, lk+1=4lk(1−lk)l_{k+1} = 4l_k(1 - l_k), which uses lkl_k twice per step. Already l3′l_3' follows from sympy.diff as:

16*x*(1 - x)*(8*x - 4) - 16*x*(-4*x*(1 - x) + 1) + 16*(1 - x)*(-4*x*(1 - x) + 1)

Size explodes: in the second symbolic cell, count_ops counts 21 operations in l3′l_3', 264 in l5′l_5' and 2,096 in l7′l_7', while l7l_7 has 158. Expanding the polynomial does not help: ln′l_n' has degree 2n−1−12^{n-1} - 1, and term count also doubles each step.

InteractiveExpression growth
Expanded tree of l1′l_1': each occurrence is a rectangle
Graph with shared subexpressions of l1l_1 and l1′l_1' (columns: iteration kk)
x1
Size versus nn (log scale)
tree of l′ₙtree of lₙgraph of lₙ and l′ₙ
110¹10²10³10⁴10⁵10⁶124681012iteration n
Color of the iteration when the subexpression is created:k = 1
n = 1
Iteration nn1
Nodes in the lnl_n tree1
Nodes in the ln′l_n' tree1
Distinct nodes of lnl_n and ln′l_n' together (graph)2
Occurrences of xx in the ln′l_n' tree0
l1=xl_1 = x and l1′=1l_1' = 1. Advance: each iteration uses lkl_k twice.
Above, the expanded tree of ln′l_n', built using product and subtraction rules (simplifying only zeros and ones): each subexpression occurrence is a rectangle, width proportional to its leaves, colored by iteration kk where it originates. Below, the same calculation with shared subexpressions: each lkl_k and lk′l_k' appears once. The size graph shows exact counts up to n=12n = 12 on a logarithmic scale. Start at n=4n = 4 and play the animation: the tree repeats identical blocks, while the graph reuses them.

The interactive counts nodes in an explicit model (a binary tree with ++, −-, ×\times and negation), different from SymPy’s operation count, but the story is the same: the ln′l_n' tree grows from 44 nodes at n=3n = 3 to 27,136 at n=10n = 10, multiplying by slightly more than 2 per iteration; the shared-subexpression graph adds exactly 8 nodes per iteration, 73 total at n=10n = 10. Explosion is a property of representation, not the derivative: a tree cannot say “reuse the earlier result.”

Common subexpression elimination (sympy.cse) restores sharing: find repeated subtrees, name them and return assignments. With cse, l7′l_7' falls from 2,096 operations to 93 and growth becomes nearly linear. That list is a sequence of elementary operations, each intermediate saved and reused: exactly the evaluation trace starting automatic differentiation. Baydin et al. (2018) describe AD this way: symbolically differentiate each elementary operation and save intermediate numerical results. The next lesson starts there.

Symbolic differentiation has another limit no cse fixes: it requires the function as a closed expression. A program with data-dependent loops, if on intermediates or calls to an iterative solver is not an expression; AD differentiates its concrete execution.

Gradient checking

Now build the tool motivating the lesson.

Each procedural choice builds on what you have seen:

  1. Central differences in float64 with h≈ε1/3max⁡(1,∣θj∣)h \approx \eps^{1/3}\max(1, \abs{\theta_j}). With u=2−53u = 2^{-53} and order-1 scales, expected error is about 10−1010^{-10}; threshold 10−610^{-6} leaves four orders of margin. In float32, u=2−24u = 2^{-24} and the same calculation yields optimal error (3u)2/3/2≈1.6×10−5(3u)^{2/3}/2 \approx 1.6\times 10^{-5} at unit scales, practically 10−410^{-4} to 10−310^{-3}: the necessary threshold can miss a real 0.01% error.
  2. Relative, not absolute error. A correct gradient with components 10410^4 has finite-difference absolute errors 10−410^{-4}; one with components 10−610^{-6} can be completely wrong with absolute error 10−610^{-6}. Relative error is invariant under scaling ff.
  3. A generic point. Avoid θ=0\theta = 0 (many terms vanish and an error multiplied by zero is invisible), ties or zero preactivations: at a kink, central differences average both slopes and raise a false alarm no hh fixes.
  4. Random directions for large models. Comparing g⊤v\vb{g}\T\vb{v} with numerical directional derivatives for a few random v\vb{v} costs 2 evaluations per direction instead of 2n2n. An error in any component appears in almost every random direction because v\vb{v} has nonzero components in all coordinates with probability 1.
  5. Taylor test for confirmation. If g\vb{g} is the gradient, remainder ∣f(θ+hv)−f(θ)−h g⊤v∣\abs{f(\theta + h\vb{v}) - f(\theta) - h\,\vb{g}\T\vb{v}} is O(h2)\bigO(h^2) by multivariable Taylor expansion; if g\vb{g} is wrong in direction v\vb{v}, remainder is O(h)\bigO(h). Measuring log–log slope (empirical order verification) needs no threshold. This is the gradient Taylor test used in inverse problems with adjoints.
InteractiveThe checker and its traps
10⁻¹⁶10⁻¹²10⁻⁸10⁻⁴1relative errorW₁₁W₁₂W₂₁W₂₂W₃₁W₃₂b₁b₂b₃v₁v₂v₃cthreshold 1.0·10⁻⁶parameter
Analytic gradient
Loss precision
10⁻⁶
Maximum relative error…
Acceptance threshold1.0·10⁻⁶
Components above threshold…
Worst component…
Analytic…
Numeric…
Computing central differences…
A tiny network (2 inputs, 3 ReLU neurons, 16 examples generated with a fixed seed) with mean-square loss plus (λ/2)∥W∥2(\lambda/2)\norm{\mat{W}}^2, λ=10−4\lambda = 10^{-4}. Bars show relative error of each of 13 analytic-gradient components against central differences; the line is the threshold (10−610^{-6} in float64, 10−210^{-2} in float32). Initially a subtle bug omits λW\lambda\mat{W} from the gradient. Inspect float64, then switch to float32 and find an hh passing the correct gradient: can you still see the bug? Also try the kink, a ReLU with preactivation exactly 0 on one example.

For these particular data, the figure shows: in float64 with h=10−6h = 10^{-6}, the correct gradient has relative error at most 7×10−97\times 10^{-9}, whereas the λW\lambda\mat{W} bug yields 1.2×10−41.2\times 10^{-4} to 2.3×10−32.3\times 10^{-3} in the six components of W\mat{W}: over four orders of separation, with the threshold between them. In float32 with h=10−6h = 10^{-6} even the correct gradient fails: some errors exceed 1 because the loss difference is only a few float32 ulps. With h=10−2h = 10^{-2} the correct one falls below threshold (at most 1.8×10−41.8\times 10^{-4}), but so does the one omitting λW\lambda\mat{W} (2.4×10−32.4\times 10^{-3}): float32 cannot distinguish them. With h≤10−7.75h \le 10^{-7.75}, θj±h\theta_j \pm h rounds to θj\theta_j for components near magnitude 1 (float32 ulp at 1 is 1.2×10−71.2\times 10^{-7}): effective step is 0 and the quotient is NaN. At the kink, the correct gradient fails in the affected neuron’s three components (W11W_{11}, W12W_{12} and b1b_1, errors 0.24, 0.24 and 0.47), with the same errors for h=10−6h = 10^{-6} and h=10−3h = 10^{-3}.

Lab: finite differences, complex step and checker

Start with four single-variable formulas and the V curve for the figure’s three functions. Exact derivatives are closed-form.

[ ]Finite differences from scratch and the V curveBrowser
import numpy as np

def progresiva(f, x, h):
    return (f(x + h) - f(x)) / h

def centrada(f, x, h):
    return (f(x + h) - f(x - h)) / (2 * h)

def cuarto_orden(f, x, h):
    return (-f(x + 2*h) + 8*f(x + h) - 8*f(x - h) + f(x - 2*h)) / (12 * h)

def paso_complejo(f, x, h):
    return np.imag(f(x + 1j * h)) / h

# función de prueba de Martins, Sturdza y Alonso (2003) y su derivada exacta
def f_st(x):
    return np.exp(x) / np.sqrt(np.sin(x)**3 + np.cos(x)**3)

def df_st(x):
    s, c = np.sin(x), np.cos(x)
    g, dg = s**3 + c**3, 3*s*s*c - 3*c*c*s
    return f_st(x) * (1 - dg / (2 * g))

casos = {"exp en x = 1": (np.exp, 1.0, np.exp(1.0)),
         "Squire-Trapp en x = 1.5": (f_st, 1.5, df_st(1.5)),
         "1e6 + sin x en x = 1": (lambda x: 1e6 + np.sin(x), 1.0, np.cos(1.0))}
metodos = {"progresiva": progresiva, "centrada": centrada,
           "cuarto orden": cuarto_orden, "paso complejo": paso_complejo}
hs = 10.0 ** np.arange(-20, -0.49, 0.05)

for nombre, (f, x0, d) in casos.items():
    print(nombre)
    for m, D in metodos.items():
        err = np.array([abs(D(f, x0, h) - d) / abs(d) for h in hs])
        i = np.argmin(err)
        print(f"  {m:14s} mejor h = {hs[i]:.1e}   error = {err[i]:.1e}"
              f"   error con h = 1e-15: {err[np.argmin(abs(hs - 1e-15))]:.1e}"
              + (f"   peor error con h <= 1e-8: {err[hs <= 1e-8].max():.1e}" if m == "paso complejo" else ""))

u = 2.0**-53
print("\nmodelo con |f| = |f''| = |f'''| = |f^(5)| = 1 y eps_f = u:")
print(f"  progresiva    h* = 2 sqrt(u)     = {2*np.sqrt(u):.2e}   E* = {2*np.sqrt(u):.2e}")
print(f"  centrada      h* = (3u)^(1/3)    = {(3*u)**(1/3):.2e}   E* = {(3*u)**(2/3)/2:.2e}")
h4 = (11.25*u)**0.2
print(f"  cuarto orden  h* = (45u/4)^(1/5) = {h4:.2e}   E* = {h4**4/30 + 1.5*u/h4:.2e}")

# el paso que de verdad se usa no es h, sino (x + h) - x
x, h = 1.0, 1e-8
print(f"\n(x + h) - x = {(x + h) - x!r}, error relativo respecto a h: {((x + h) - x - h) / h:.1e}")

All three V curves bottom out where the model predicts, and complex step gives zero error or error of order uu across h≤10−8h \le 10^{-8}. With h=10−15h = 10^{-15}, forward differences lose every digit at 106+sin⁡x10^6 + \sin x (relative error 1: f(x+h)f(x + h) and f(x)f(x) are the same floating-point number, so their difference is exactly 0), and fourth order is wrong by a factor 1.8×1041.8\times 10^4.

Now Fornberg’s algorithm. For each new node xix_i it updates weights of previous nodes and computes the new one’s using a matrix-free recurrence; the loop performs on the order of n2Mn^2 M operations for nn nodes and derivatives through MM. Function orden finds the Taylor table’s first nonzero moment.

[ ]Fornberg weights and stencil orderBrowser
import numpy as np
from fractions import Fraction
from math import factorial

def fornberg(z, x, M):
    """Pesos c[j, k] de la derivada k-ésima (k = 0..M) en z con los nodos x[0..n] (Fornberg)."""
    x = np.asarray(x, dtype=float)
    n = len(x) - 1
    c = np.zeros((n + 1, M + 1))
    c[0, 0] = 1.0
    c1, c4 = 1.0, x[0] - z
    for i in range(1, n + 1):
        mn = min(i, M)
        c2, c5, c4 = 1.0, c4, x[i] - z
        for j in range(i):
            c3 = x[i] - x[j]
            c2 *= c3
            if j == i - 1:                      # pesos del nodo nuevo
                for k in range(mn, 0, -1):
                    c[i, k] = c1 * (k * c[i - 1, k - 1] - c5 * c[i - 1, k]) / c2
                c[i, 0] = -c1 * c5 * c[i - 1, 0] / c2
            for k in range(mn, 0, -1):          # actualización de los anteriores
                c[j, k] = (c4 * c[j, k] - k * c[j, k - 1]) / c3
            c[j, 0] = c4 * c[j, 0] / c3
        c1 = c2
    return c

def orden(s, w, m):
    """Primer momento no nulo mu_k = sum_j w_j s_j^k / k! con k > m: error ~ mu_k h^(k-m) f^(k)."""
    for k in range(m + 1, len(s) + 5):
        mu = sum(wj * sj**k for wj, sj in zip(w, s)) / factorial(k)
        if abs(mu) > 1e-10:
            return k - m, mu
    return None, 0.0

def frac(v):
    return str(Fraction(v).limit_denominator(10000))

plantillas = [("progresiva", [0, 1], 1), ("centrada", [-1, 0, 1], 1), ("unilateral 3", [0, 1, 2], 1),
              ("centrada 5", [-2, -1, 0, 1, 2], 1), ("segunda, 3", [-1, 0, 1], 2),
              ("irregular", [-1, 0, 0.5, 2], 1)]
for nombre, s, m in plantillas:
    w = fornberg(0.0, s, m)[:, m]
    p, C = orden(s, w, m)
    print(f"{nombre:13s} m={m}  pesos = [{', '.join(frac(v) for v in w)}]   orden {p}, C = {frac(C)}")

# el orden, medido: al dividir h por 2 el error debe dividirse por 2^p
f = lambda x: np.exp(np.sin(x))
d1 = np.cos(0.6) * f(0.6)
s = [0, 1, 2]
w = fornberg(0.0, s, 1)[:, 1]
print("\nunilateral de 3 nodos sobre e^{sin x} en x = 0.6:")
anterior = None
for h in [0.1, 0.05, 0.025, 0.0125]:
    e = abs(sum(wj * f(0.6 + sj * h) for wj, sj in zip(w, s)) / h - d1)
    print(f"  h = {h:<7} error = {e:.3e}" + (f"   cociente = {anterior / e:.2f}" if anterior else ""))
    anterior = e

Weights and constants match the text, and error ratios when halving hh approach 4: order 2, checked without knowing the constant.

The Richardson table on central differences, with large and small initial steps:

[ ]Richardson for derivativesBrowser
import numpy as np

def richardson_derivada(f, x, h0, niveles=6):
    """Tabla de Richardson sobre la centrada: T[i][j] elimina los términos h^2, ..., h^(2j)."""
    T = [[0.0] * niveles for _ in range(niveles)]
    h = h0
    for i in range(niveles):
        T[i][0] = (f(x + h) - f(x - h)) / (2 * h)
        for j in range(1, i + 1):
            T[i][j] = T[i][j - 1] + (T[i][j - 1] - T[i - 1][j - 1]) / (4**j - 1)
        h /= 2
    return T

f, x0, exacta = np.exp, 1.0, np.exp(1.0)
T = richardson_derivada(f, x0, 0.4)
print("error relativo (filas: h = 0.4, 0.2, ...; columnas: nivel de extrapolación)")
for i, fila in enumerate(T):
    print(f"h = {0.4 / 2**i:<8.4g}" + "  ".join(f"{abs(v - exacta) / exacta:9.1e}" for v in fila[: i + 1]))

# un nivel de Richardson sobre la centrada es la fórmula de cinco puntos con paso h/2
h = 0.1
D = lambda h: (f(x0 + h) - f(x0 - h)) / (2 * h)
rich = (4 * D(h / 2) - D(h)) / 3
k = h / 2
cinco = (-f(x0 + 2*k) + 8*f(x0 + k) - 8*f(x0 - k) + f(x0 - 2*k)) / (12 * k)
print(f"\n(4 D(h/2) - D(h)) / 3 = {float(rich)!r}\nfórmula de 5 puntos    = {float(cinco)!r}")

T = richardson_derivada(f, x0, 1e-4)
print("\ncon h0 = 1e-4, error de la diagonal:", "  ".join(f"{abs(T[i][i] - exacta)/exacta:.1e}" for i in range(6)))

The two five-point formulas differ only in the last bit because operation order differs. With h0=0.4h_0 = 0.4 the level-3 column reaches 1.8×10−151.8\times 10^{-15} and the table stalls at 10−1410^{-14}; with h0=10−4h_0 = 10^{-4} the first level already reaches 3×10−133\times 10^{-13} and later levels worsen.

Complex step and what breaks it:

[ ]Complex step and what breaks itBrowser
import numpy as np
import warnings

def f_st(x):
    return np.exp(x) / np.sqrt(np.sin(x)**3 + np.cos(x)**3)

s, c = np.sin(1.5), np.cos(1.5)
exacta = f_st(1.5) * (1 - (3*s*s*c - 3*c*c*s) / (2 * (s**3 + c**3)))
for h in [1e-4, 1e-8, 1e-20, 1e-100, 1e-300]:
    d = np.imag(f_st(1.5 + 1j * h)) / h
    print(f"h = {h:.0e}   paso complejo = {d:.17f}   error relativo = {abs(d - exacta) / exacta:.1e}")
print(f"exacta                       {exacta:.17f}")

# la segunda derivada con la parte real vuelve a restar
for h in [1e-4, 1e-20]:
    print(f"f'' = 2 (f(x) - Re f(x + ih)) / h^2 con h = {h:.0e}: {2 * (f_st(1.5) - np.real(f_st(1.5 + 1j * h))) / h**2:.6g}")

x, h = 0.7, 1e-20
def cs(f):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        try:
            return f"{np.imag(f(x + 1j * h)) / h:.6g}"
        except TypeError:
            return "TypeError"
pruebas = [
    ("np.tanh(z)", lambda z: np.tanh(z), 1 - np.tanh(x)**2),
    ("np.log1p(z)", lambda z: np.log1p(z), 1 / (1 + x)),
    ("np.sqrt(np.sum(v**2))", lambda z: np.sqrt(np.sum(np.array([z, 1.0])**2)), x / np.hypot(x, 1)),
    ("np.abs(z)**3", lambda z: np.abs(z)**3, 3 * x**2),
    ("np.linalg.norm(v)", lambda z: np.linalg.norm(np.array([z, 1.0])), x / np.hypot(x, 1)),
    ("np.vdot(v, v)", lambda z: np.vdot(np.array([z, 2.0]), np.array([z, 2.0])), 2 * x),
    ("np.sign(z) * z**2", lambda z: np.sign(z) * z**2, 2 * x),
    ("v.astype(float)**2", lambda z: np.array([z]).astype(float)[0]**2, 2 * x),
    ("float(z)**2", lambda z: float(z)**2, 2 * x),
    ("z > 0 (escalar)", lambda z: z**2 if z > 0 else 0.0, 2 * x),
    ("np.where(arr > 0, ...)", lambda z: np.where(np.array([z]) > 0, np.array([z])**2, 0.0)[0], 2 * x),
    ("np.arctan2(z, 1)", lambda z: np.arctan2(z, 1.0), 1 / (1 + x * x)),
    ("np.logaddexp(z, 0)", lambda z: np.logaddexp(z, 0.0), 1 / (1 + np.exp(-x))),
]
print(f"\n{'expresión':24s} {'paso complejo':>14s} {'exacta':>10s}")
for nombre, f, d in pruebas:
    print(f"{nombre:24s} {cs(f):>14s} {d:10.6g}")

def abs_cs(z):
    """|x| extendida analíticamente a cada lado de 0: conserva la parte imaginaria."""
    return np.where(np.real(z) < 0, -z, z)
print(f"\ncon abs_cs: derivada de |x|^3 en x = -0.7 = {np.imag(abs_cs(-0.7 + 1e-20j)**3) / 1e-20:.6g}"
      f"   (exacta {-3 * 0.49:.6g})")

Elementary holomorphic functions (tanh, log1p, a manually written square root of a sum of squares) work. Modulus or conjugation returns 0, sign silently gives a false value, and scalar conversions or comparisons fail with TypeError. Array comparisons work because NumPy orders complex numbers by real part first. Silent failures such as abs or norm are dangerous; Martins, Sturdza and Alonso therefore redefine these functions before applying the method to large code.

Finally, the checker. The first function compares directional derivatives in random directions: use it with large models and the following lessons’ AD engines. The model is a perceptron with one hidden layer of 8 tanh neurons, 64 examples and regularization λ=10−5\lambda = 10^{-5}; the gradient is handwritten with optional bugs.

[ ]Gradient checking with random directionsBrowser
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(64, 5))
y = np.sin(X[:, 0]) + 0.5 * X[:, 1] + 0.1 * rng.normal(size=64)
LAM = 1e-5
FORMAS = [(8, 5), (8,), (8,), ()]
N_PARAM = sum(int(np.prod(f)) for f in FORMAS)

def desempaqueta(theta):
    partes, i = [], 0
    for f in FORMAS:
        k = int(np.prod(f))
        partes.append(theta[i:i + k].reshape(f))
        i += k
    return partes

def perdida(theta, dtype=np.float64):
    W1, b1, w2, b2 = (p.astype(dtype) for p in desempaqueta(theta.astype(dtype)))
    Xd, yd = X.astype(dtype), y.astype(dtype)
    a = np.tanh(Xd @ W1.T + b1)
    r = a @ w2 + b2 - yd
    return np.mean(r * r) + dtype(LAM / 2) * np.sum(W1 * W1)

def gradiente(theta, fallo=None):
    W1, b1, w2, b2 = desempaqueta(theta)
    a = np.tanh(X @ W1.T + b1)
    r = a @ w2 + b2 - y
    dr = (1.0 if fallo == "factor 2" else 2.0) * r / len(y)
    gw2, gb2 = a.T @ dr, dr.sum()
    dz = np.outer(dr, w2) * (1 - a * a)
    gW1, gb1 = dz.T @ X, dz.sum(axis=0)
    if fallo != "sin lambda W":
        gW1 = gW1 + LAM * W1
    if fallo == "signo":
        gb1 = gb1.copy(); gb1[3] = -gb1[3]
    return np.concatenate([gW1.ravel(), gb1, gw2, [gb2]])

def comprueba_direcciones(f, g, theta, k=8, h=None, semilla=1):
    """Máximo error relativo de k derivadas direccionales: 2 evaluaciones de f por dirección."""
    rng = np.random.default_rng(semilla)
    h = h if h is not None else (3 * 2.0**-53) ** (1 / 3) * max(1.0, np.max(np.abs(theta)))
    gt = g(theta)
    peor = 0.0
    for _ in range(k):
        v = rng.normal(size=theta.shape)
        v /= np.linalg.norm(v)
        num = (f(theta + h * v) - f(theta - h * v)) / (2 * h)
        ana = gt @ v
        peor = max(peor, abs(num - ana) / max(abs(num), abs(ana), 1e-300))
    return peor

theta = 0.5 * rng.normal(size=N_PARAM)
print(f"{N_PARAM} parámetros; con 8 direcciones: 16 evaluaciones en lugar de {2 * N_PARAM}")
for fallo in [None, "signo", "factor 2", "sin lambda W"]:
    e64 = comprueba_direcciones(perdida, lambda t: gradiente(t, fallo), theta)
    e32 = comprueba_direcciones(lambda t: perdida(t, np.float32), lambda t: gradiente(t, fallo), theta, h=1e-2)
    print(f"gradiente {str(fallo or 'correcto'):13s}  float64: {e64:.1e}   float32 (h = 1e-2): {e32:.1e}")

# prueba de Taylor: el resto f(θ + hv) - f(θ) - h g·v es O(h^2) solo si g es el gradiente
v = rng.normal(size=N_PARAM); v /= np.linalg.norm(v)
print("\nprueba de Taylor (resto frente a h = 1e-1 ... 1e-5)")
for fallo in [None, "sin lambda W"]:
    g = gradiente(theta, fallo)
    restos = [abs(perdida(theta + h * v) - perdida(theta) - h * (g @ v)) for h in [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]]
    pend = [np.log10(restos[i] / restos[i + 1]) for i in range(4)]
    print(f"  {str(fallo or 'correcto'):13s} restos = {', '.join(f'{r:.1e}' for r in restos)}"
          f"   pendientes = {', '.join(f'{p:.2f}' for p in pend)}")

# un pliegue: f(w) = sum relu(w) + |w|^2 / 2 en un punto con w_2 = 0
f = lambda w: np.maximum(w, 0).sum() + 0.5 * w @ w
gw = lambda w: (w > 0).astype(float) + w           # convenio relu'(0) = 0, como PyTorch
w = np.array([0.3, 0.0, -0.2])
num = np.array([(f(w + 1e-6 * e) - f(w - 1e-6 * e)) / 2e-6 for e in np.eye(3)])
print(f"\npliegue: analítico = {gw(w)}, numérico = {np.round(num, 6)}")

Read the output carefully; it summarizes the lesson:

  • In float64, the correct gradient gives 2.6×10−92.6\times 10^{-9} and the three bugs 0.740.74, 0.500.50 and 2.0×10−42.0\times 10^{-4}. The λW\lambda\mat{W} bug is subtle (a term of size 10−510^{-5}) but almost five orders above noise.
  • In float32, the correct gradient gives 4.7×10−44.7\times 10^{-4} and the one omitting λW\lambda\mat{W} gives 2.6×10−42.6\times 10^{-4}: less than the correct one. No threshold separates them.
  • The correct gradient’s Taylor test has slope 2.002.00 throughout; the gradient omitting λW\lambda\mat{W} starts at 2 (large hh makes the quadratic term dominate) and falls to 1.331.33 between h=10−4h = 10^{-4} and 10−510^{-5}, toward 1 as linear error takes over.
  • At the kink, the correct gradient (under convention ReLU⁡′(0)=0\relu'(0) = 0) gives 0 in the second component and central differences give 0.5, the mean of both slopes.

Symbolic differentiation with SymPy

The second lab measures expression growth in the logistic map, the effect of cse and evaluation cost.

[ ]SymPy: growth, cse and lambdifyBrowser
import time
import numpy as np
import sympy as sp

x = sp.Symbol("x")
l = x
print(" n   ops(l_n)   ops(l_n')   ops(expand(l_n'))   ops con cse")
for n in range(1, 8):
    d = sp.diff(l, x)
    sustituciones, (reducida,) = sp.cse(d)
    ops_cse = sum(sp.count_ops(e) for _, e in sustituciones) + sp.count_ops(reducida)
    exp_ops = sp.count_ops(sp.expand(d)) if n <= 6 else None
    print(f"{n:2d} {sp.count_ops(l):10d} {sp.count_ops(d):11d} "
          f"{str(exp_ops if exp_ops is not None else '-'):>19s} {ops_cse:14d}")
    if n == 7:
        d7, l7 = d, l
    l = 4 * l * (1 - l)

print("\nl_3' tal cual sale de sympy.diff:\n ", sp.diff(4*(4*x*(1 - x))*(1 - 4*x*(1 - x)), x))

# tres maneras de evaluar l_7'(x) en 50 000 puntos
xs = np.linspace(0.0, 1.0, 50_000)
f_sin = sp.lambdify(x, d7, "numpy", cse=False)
f_cse = sp.lambdify(x, d7, "numpy", cse=True)
f_l7 = sp.lambdify(x, l7, "numpy", cse=True)
def mide(fn, rep=3):
    t = time.perf_counter()
    for _ in range(rep):
        fn()
    return (time.perf_counter() - t) / rep
t_sin = mide(lambda: f_sin(xs))
t_cse = mide(lambda: f_cse(xs))
h = 1e-5
t_fd = mide(lambda: (f_l7(xs + h) - f_l7(xs - h)) / (2 * h))
ref = f_cse(xs)
err_fd = np.max(np.abs((f_l7(xs + h) - f_l7(xs - h)) / (2 * h) - ref) / np.maximum(1.0, np.abs(ref)))
print(f"\nl_7' sin cse: {t_sin*1e3:.1f} ms   con cse: {t_cse*1e3:.1f} ms   diferencias centradas: {t_fd*1e3:.1f} ms")
print(f"coinciden sin y con cse: {np.allclose(f_sin(xs), ref, rtol=1e-9, atol=1e-6)}"
      f"   error de las centradas (relativo a max(1, |l'|)): {err_fd:.1e}")

The table confirms the figure under another size model: operations of ln′l_n' grow by slightly less than threefold per iteration (768 to 2,096 between n=6n = 6 and n=7n = 7), expanded-form operations double (44 to 92 between n=5n = 5 and n=6n = 6, the polynomial degree), and cse form grows only slightly faster than linearly (67 and 93). Browser timings vary by run, but their order is robust: unshared evaluation costs over ten times cse evaluation, as the operation ratio suggests (2,096 versus 93). Central differences evaluate l7l_7 only twice and are cheapest but have 1.8% error: l7l_7 is a degree-64 polynomial with enormous high derivatives, so truncation h2f′′′/6h^2 f'''/6 with h=10−5h = 10^{-5} is no longer small. AD will combine symbolic accuracy with numerical cost.

In libraries

  • scipy.optimize.approx_fprime(x, f, epsilon) computes gradients using forward differences, with default epsilon ε≈1.49×10−8\sqrt{\eps} \approx 1.49\times 10^{-8} (a scalar or component vector). A custom central difference is better for checking.
  • scipy.optimize.check_grad(f, grad, x0) returns the 2-norm of the difference between grad(x0) and approx_fprime: an absolute error. With direction="random" it compares in one random direction.
  • torch.autograd.gradcheck(fn, inputs) compares the Jacobian from backward against central differences, with defaults eps=1e-6, atol=1e-5 and rtol=1e-3, accepting if ∣a−n∣≤atol+rtol ∣n∣\abs{a - n} \le \text{atol} + \text{rtol}\,\abs{n} for every entry. It warns when inputs are not double precision.
  • sympy.diff, sympy.cse and sympy.lambdify(..., cse=True) differentiate, share subexpressions and generate a NumPy function, as in the lab.
[ ]check_grad measures absolute errorBrowser
import numpy as np
from scipy.optimize import approx_fprime, check_grad

x0 = np.array([0.3, -1.2, 2.0])
grande = lambda x: 1e4 * np.sum(np.exp(x))
g_grande = lambda x: 1e4 * np.exp(x)                    # correcto
pequena = lambda x: 1e-6 * np.sum(x**2)
g_pequena_mal = lambda x: 1e-6 * x                      # falta el 2

print("approx_fprime (progresiva):", approx_fprime(x0, grande))
print("gradiente exacto:          ", g_grande(x0))

def centrada(f, x, h=6e-6):
    hs = h * np.maximum(1.0, np.abs(x))
    return np.array([(f(x + hj * e) - f(x - hj * e)) / (2 * hj) for hj, e in zip(hs, np.eye(len(x)))])

def rel_max(g, gn):
    return np.max(np.abs(g - gn) / np.maximum(np.maximum(np.abs(g), np.abs(gn)), 1e-300))

for nombre, f, g in [("grande, correcto", grande, g_grande), ("pequeña, sin el 2", pequena, g_pequena_mal)]:
    print(f"{nombre:18s} check_grad = {check_grad(f, g, x0):.1e}"
          f"   error relativo máximo (centradas) = {rel_max(g(x0), centrada(f, x0)):.1e}")

check_grad returns a number about 600 times larger for the correct gradient (1.4×10−31.4\times 10^{-3}) than for the incorrect one (2.4×10−62.4\times 10^{-6}): it measures the scale of ff, not gradient quality. Relative error separates them by ten orders of magnitude.

Now gradcheck on a PyTorch function with handwritten backward pass and two bugs: one gross (use σ(2x)\sigma(2x) instead of σ(x)\sigma(x)) and one precision-related (compute sigmoid in float32 within float64 backward). This cell requires PyTorch and runs locally.

[ ]torch.autograd.gradcheck and its tolerancesLocal GPU
import warnings
import torch
from torch.autograd.gradcheck import GradcheckError

class SoftplusAMano(torch.autograd.Function):
    """softplus(x) = log(1 + e^x) con el backward escrito a mano. Derivada correcta: sigmoid(x)."""
    @staticmethod
    def forward(ctx, x, fallo):
        ctx.save_for_backward(x)
        ctx.fallo = fallo
        return torch.nn.functional.softplus(x)

    @staticmethod
    def backward(ctx, grad_out):
        (x,) = ctx.saved_tensors
        if ctx.fallo == "sigmoid(2x)":
            s = 0.5 * (1 + torch.tanh(x))                # = sigmoid(2x): parecida, pero otra función
        elif ctx.fallo == "sigmoid en float32":
            s = torch.sigmoid(x.float()).to(x.dtype)       # pierde precisión sin avisar
        else:
            s = torch.sigmoid(x)
        return grad_out * s, None

torch.manual_seed(0)
configs = [("float64, tolerancias por defecto", torch.float64, {}),
           ("float32, tolerancias por defecto", torch.float32, {}),
           ("float64, atol=1e-9, rtol=1e-8", torch.float64, dict(atol=1e-9, rtol=1e-8))]
for nombre, dtype, tol in configs:
    x = torch.randn(20, dtype=dtype, requires_grad=True)
    print(nombre)
    for fallo in (None, "sigmoid(2x)", "sigmoid en float32"):
        with warnings.catch_warnings(record=True) as avisos:
            warnings.simplefilter("always")
            try:
                torch.autograd.gradcheck(lambda t: SoftplusAMano.apply(t, fallo), (x,), **tol)
                res = "pasa"
            except GradcheckError:
                res = "falla (Jacobian mismatch)"
        aviso = "  [aviso: la entrada no es float64]" if any("double precision" in str(a.message) for a in avisos) else ""
        print(f"   backward {str(fallo or 'correcto'):20s} {res}{aviso}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With default tolerances and float64, gradcheck detects the gross bug but misses the precision bug: float32 sigmoid relative error of order u32=2−24≈6×10−8u_{32} = 2^{-24} \approx 6\times 10^{-8} easily fits within rtol=1e-3. In float32 everything fails, including correct backward, with a warning that input is not double precision. Tolerances tuned to actual float64 central-difference error (≈10−10\approx 10^{-10}) reveal the precision bug too. Defaults avoid false alarms rather than find small bugs; tune them when writing your own backward.

Common mistakes

Exercises

NumericOptimal forward-difference step
With model E(h)=M22h+2εfM0hE(h) = \tfrac{M_2}{2}h + \tfrac{2\eps_f M_0}{h}, where M0=∣f(x)∣=1M_0 = \abs{f(x)} = 1, M2=∣f′′∣=1M_2 = \abs{f''} = 1 and each evaluation of ff is correctly rounded in float64 (εf=u=2−53≈1.11×10−16\eps_f = u = 2^{-53} \approx 1.11\times 10^{-16}), what step hh minimizes the bound?
NumericCentral-difference digits in float32
For central-difference model E(h)=M36h2+εfM0hE(h) = \tfrac{M_3}{6}h^2 + \tfrac{\eps_f M_0}{h}, M0=M3=1M_0 = M_3 = 1 and εf=u=2−24\eps_f = u = 2^{-24} (float32), what is the minimum of bound EE?
NumericA one-sided second derivative
Construct f′′(x)≈h−2[w0f(x)+w1f(x+h)+w2f(x+2h)+w3f(x+3h)]f''(x) \approx h^{-2}\big[w_0 f(x) + w_1 f(x + h) + w_2 f(x + 2h) + w_3 f(x + 3h)\big], exact for polynomials of degree ≤3\le 3. What is w1w_1?
NumericOne Richardson step
For f(x)=exf(x) = e^x at x=0x = 0, central difference is D0(h)=sinh⁡(h)/hD_0(h) = \sinh(h)/h: D0(0.2)=1.0066800127D_0(0.2) = 1.0066800127 and D0(0.1)=1.0016675002D_0(0.1) = 1.0016675002. What does one Richardson extrapolation step produce from these values?
ProofCentral-difference error and optimal step
Prove: If f∈C3f \in C^3 near xx, ∣f′′′∣≤M3\abs{f'''} \le M_3, ∣f∣≤M0\abs{f} \le M_0 and each evaluation of ff has relative error ≤εf\le \eps_f, then computed central-difference error is at most E(h)=M3h26+εfM0hE(h) = \tfrac{M_3h^2}{6} + \tfrac{\eps_f M_0}{h}, minimized at h∗=(3εfM0/M3)1/3h_\ast = (3\eps_f M_0/M_3)^{1/3} with E(h∗)∝εf2/3E(h_\ast) \propto \eps_f^{2/3}.
0
Separate truncation (exact arithmetic) from rounding (evaluation of ff).

Step 1 of 4. Which expansions give truncation error?

QuizWhy complex step works and what breaks it
For Im⁡f(x+ih)/h\operatorname{Im} f(x + ih)/h with ff real analytic at xx and h=10−20h = 10^{-20}, which statements are true?

More than one answer may be correct.

QuizGradient of a large model
A model has 10710^7 parameters and evaluating its loss takes 1 s. How long would a full central-difference gradient take?
QuizReading a verification report
You check a new ReLU layer whose backward treats all neurons with the same vectorized code, using central differences in float64 with h=10−6h = 10^{-6}. All components have relative error between 10−1110^{-11} and 10−910^{-9} except three, at 0.240.24, 0.230.23 and 0.470.47: two weights and the bias of one neuron. Changing hh to 10−410^{-4} leaves them at 0.240.24, 0.230.23 and 0.470.47. What is most likely?
QuizWhat cse does
Which statement about symbolic differentiation of lk+1=4lk(1−lk)l_{k+1} = 4l_k(1 - l_k) is correct?
CodeA componentwise gradient checker
Implement grad_check(f, grad_f, x, eps=None), returning the maximum componentwise relative error between grad_f(x) and the central-difference gradient of f at x (a float64 array). For each component use step hj=eps⋅max⁡(1,∣xj∣)h_j = \text{eps}\cdot\max(1, \abs{x_j}), default eps (3u)1/3(3u)^{1/3}, u=2−53u = 2^{-53}; component jj relative error is ∣gj−g^j∣/max⁡(∣gj∣,∣g^j∣)\abs{g_j - \hat g_j}/\max(\abs{g_j}, \abs{\hat g_j}), or 0 if both are 0. Do not modify x. Tests check that a correct gradient gives less than 10−610^{-6} and a changed sign, missing factor 2 or missing small term exceeds 10−510^{-5}, also when function scale is 10610^6 or 10−810^{-8} (where absolute error fails).
import numpy as np

def grad_check(f, grad_f, x, eps=None):
  """Máximo error relativo por componente entre grad_f(x) y las diferencias centradas de f."""
  x = np.asarray(x, dtype=float)
  if eps is None:
      eps = (3 * 2.0**-53) ** (1 / 3)
  g = np.asarray(grad_f(x), dtype=float)
  # tu código: gradiente numérico componente a componente y error relativo
  return 0.0
Shift+Enter to run

Connections and further reading

Further reading: Squire and Trapp (1998) is three pages; Martins, Sturdza and Alonso (2003) explain converting large programs to complex step and its relation to AD; Fornberg (1988) gives the full weight recurrence; and section 2 of Baydin et al. (2018) compares the three alternatives with AD.

Summary

Key idea
Differentiating by subtracting ff values loses digits to cancellation: truncation falls with hh and rounding rises like u∣f∣/hu\abs{f}/h, leaving at most half the digits for forward differences and two-thirds for central differences. Complex step avoids subtraction; AD also avoids the step.
  • Taylor table ∑jwjsjk/k!=δkm\sum_j w_j s_j^k/k! = \delta_{km} yields any difference formula; the first nonzero moment gives order and error constant, and Fornberg’s algorithm calculates weights without solving systems.
  • Total error E(h)≈Ahp+Bεf∣f∣/hmE(h) \approx Ah^p + B\eps_f\abs{f}/h^m forms a V; optimal step is h∗∝εf1/(p+m)h_\ast \propto \eps_f^{1/(p + m)} and minimum error ∝εfp/(p+m)\propto \eps_f^{p/(p + m)}: u\sqrt{u} for forward and u2/3u^{2/3} for central differences.
  • Richardson eliminates even central-error terms, permits large starting steps and one level equals the five-point formula.
  • Im⁡f(x+ih)/h\operatorname{Im} f(x + ih)/h gives f′f' to machine precision for arbitrarily small hh if all ff code is holomorphic: abs, norm, conj, sign and real conversions break it.
  • A numerical gradient costs O(n)\bigO(n) evaluations; it is useful for verification, not training.
  • Symbolic differentiation is exact, but its expression tree grows exponentially with composition; sharing subexpressions (cse) makes it linear, and that assignment list is the AD trace.
  • Check gradients in float64 using relative error at generic points away from kinks, with central differences or random directions, and confirm slope 2 with the Taylor test.