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 , 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 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 remain.
- Complex step. For analytic functions, evaluating at yields the derivative without subtraction and therefore with all digits. In exchange, code for 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, . Finite differences truncate that limit at a small but nonzero .
The error from truncating the limit in exact arithmetic is truncation error, given by the Taylor remainder.
Proof
- Taylor with Lagrange remainder: with . Subtract and divide by .
- Expand through order 3 with a remainder on each side: , with and . Subtraction cancels and the term:
The average of and lies between them; since is continuous on , the intermediate value theorem gives an in that interval where equals the average.
∎Symmetry gives an extra order: in the central difference, even Taylor terms have the same sign in and and cancel upon subtraction. For the same reason, the full expansion of has only even powers of ,
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
Taylor-expand each and group by derivative:
For the right side to equal plus small error, the “moments” must equal and for other controllable . With nodes there are unknowns, so impose for :
This is a Vandermonde system (each row is a power of the nodes divided by ), invertible for distinct nodes. This Taylor table produces all finite-difference formulas.
The proof repeats the calculation with Lagrange remainder of order at each node. With symmetric nodes and odd , weights are antisymmetric and vanishes for every even . If is even, the first candidate is even and vanishes, gaining an order: two-node stencil has order 2 rather than 1. If is odd, the center receives weight 0 (its contribution to each with is zero and antisymmetry forces it), contributing nothing: the three-node central stencil is the two-node one with an unused node, and its order 2 is the generic .
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 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.
Three observations from the figure:
- Order is not determined by node count alone. One-sided and three-node central stencils are order 2, but the one’s constant is versus : twice the error at the same . Irregular is order 3 with four nodes, as predicts.
- Higher order amplifies rounding. Sum measures amplification of error in each evaluation of . It is 1 for two-node central, 1.5 for five-node and 4 for the three-node second derivative .
- Higher derivatives are worse. Rounding error in a formula for scales as : 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 extremely small. Computers show the opposite. Compute for at with : relative error is 14%, as the lab cell prints. Subtraction fails. and agree in nearly all digits, each carrying rounding error of size ; subtraction cancels shared digits, leaving noise divided by tiny . This is catastrophic cancellation caused by the method itself.
To quantify this, suppose the program evaluating returns with . If is a correctly rounded elementary operation, , the unit roundoff; for a long program, may be much larger. Let and near . Then
The first term is the preceding theorem; the second is subtraction error (at most ) divided by . Floating-point subtraction and division add relative errors of size , negligible by comparison. This is the familiar forward error bound viewed differently: differentiation is ill-conditioned because relative input perturbation produces output change , larger as shrinks.
With and , and error is also : about 8 of the 16 digits of survive. The rule of thumb is therefore , of the same order and the default for scipy.optimize.approx_fprime. The formula’s dependence matters, not the factor 2.
For central differences, truncation is and rounding :
With all quantities of order 1 and , and : about two-thirds of the digits. Fourth order, with truncation and amplification , has and . Generally, an order- formula for the -th derivative has , minimized at with error . No difference formula reaches : higher order moves the exponent toward 1 but never reaches it.
The lab’s first cell reports, with at : best forward is with error , central with , and fourth-order with . 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 , the forward V’s bottom rises to and its best step shifts to : 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 has only even powers of : . This is exactly the Richardson extrapolation setting from quadrature: combining and eliminates term ,
Substitute the definition of and let : is exactly the five-point central formula with step . Richardson and the Taylor table reach the same result. Repeating, each level of table removes another term, . 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 is negligible, letting extrapolation remove truncation. In the cell, with and five reductions, the table reaches relative error , much better than a difference with a single . Rounding does not vanish: each level amplifies it slightly, and starting at makes the diagonal drop to at the first level then rise to . Richardson still requires choosing an initial step.
Complex step: differentiation without subtraction
If is real and analytic at , evaluate it at a nearby complex point. Expand in the imaginary direction:
Since and its derivatives are real at , odd powers of enter the imaginary part and even powers the real part. The derivative appears alone in the imaginary part, without subtraction.
Proof
Substitute into the series: . Since and are real, the imaginary part receives only odd , , with . With , dividing by yields the stated series, convergent because .
∎Truncation is the same size as central differences, . Rounding differs: without cancellation, if each complex operation has small relative error, result error is of order relative to for any . Choose small enough that is below , for example , and the derivative retains all digits. In the cell, with Martins, Sturdza and Alonso’s (2003) test function at , relative error is (one relative ulp) with and , and 0 with and ; with , truncation is visible: .
The price is that all code for must be the real function’s holomorphic extension. This excludes:
- Non-holomorphic functions.
np.abs(z)returns modulus , which is real: the imaginary part is lost and the derivative is 0. The same applies tonp.linalg.norm,np.vdotand productv.conj() @ v, which conjugate.np.sign(z)returns and a false derivative. Rewrite using each branch’s analytic extension: is if and 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 > 0raises an error; with NumPy arrays comparison is lexicographic and chooses by real part, correct except at ties. At a kink ( at 0,maxat a tie) there is no derivative to compute. - Functions without complex versions.
np.arctan2andnp.logaddexpdo not accept complex inputs.
The lab cell tests each case. Also note that gives the second derivative but subtracts : cancellation returns, and with the cell obtains instead of .
Complex step is closely related to the next lesson’s dual-number arithmetic: there evaluate with instead of , and the part accompanying is exactly , without truncation or . Complex step obtains nearly the same using the complex type available in most languages, at the cost of negligible truncation .
Cost: or evaluations per gradient
The above concerns one variable. For the gradient of , estimate each partial derivative separately by perturbing one coordinate at a time:
Forward differences need evaluations of (reusing ), central , and complex step complex evaluations. Cost grows linearly with parameter count, while neural-network ranges from millions to billions. Baydin et al. (2018) identify numerical differentiation’s complexity for a gradient in dimensions as its main machine-learning obstacle. Reverse-mode automatic differentiation computes the whole gradient at a small fixed multiple of evaluating , independent of (the cheap gradient principle). Finite differences are thus unsuitable for training but useful for checking: not every component must be checked, and directional derivative costs two evaluations for any direction .
Symbolic differentiation and expression growth
The third approach uses a computer algebra system: represent 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 or truncation error.
Composition causes trouble. Product rule copies and : if and 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 , , which uses twice per step. Already 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 , 264 in and 2,096 in , while has 158. Expanding the polynomial does not help: has degree , and term count also doubles each step.
The interactive counts nodes in an explicit model (a binary tree with , , and negation), different from SymPy’s operation count, but the story is the same: the tree grows from 44 nodes at to 27,136 at , multiplying by slightly more than 2 per iteration; the shared-subexpression graph adds exactly 8 nodes per iteration, 73 total at . 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, 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:
- Central differences in float64 with . With and order-1 scales, expected error is about ; threshold leaves four orders of margin. In float32, and the same calculation yields optimal error at unit scales, practically to : the necessary threshold can miss a real 0.01% error.
- Relative, not absolute error. A correct gradient with components has finite-difference absolute errors ; one with components can be completely wrong with absolute error . Relative error is invariant under scaling .
- A generic point. Avoid (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 fixes.
- Random directions for large models. Comparing with numerical directional derivatives for a few random costs 2 evaluations per direction instead of . An error in any component appears in almost every random direction because has nonzero components in all coordinates with probability 1.
- Taylor test for confirmation. If is the gradient, remainder is by multivariable Taylor expansion; if is wrong in direction , remainder is . Measuring log–log slope (empirical order verification) needs no threshold. This is the gradient Taylor test used in inverse problems with adjoints.
For these particular data, the figure shows: in float64 with , the correct gradient has relative error at most , whereas the bug yields to in the six components of : over four orders of separation, with the threshold between them. In float32 with even the correct gradient fails: some errors exceed 1 because the loss difference is only a few float32 ulps. With the correct one falls below threshold (at most ), but so does the one omitting (): float32 cannot distinguish them. With , rounds to for components near magnitude 1 (float32 ulp at 1 is ): effective step is 0 and the quotient is NaN. At the kink, the correct gradient fails in the affected neuron’s three components (, and , errors 0.24, 0.24 and 0.47), with the same errors for and .
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.
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 across . With , forward differences lose every digit at (relative error 1: and are the same floating-point number, so their difference is exactly 0), and fourth order is wrong by a factor .
Now Fornberg’s algorithm. For each new node it updates weights of previous nodes and computes the new one’s using a matrix-free recurrence; the loop performs on the order of operations for nodes and derivatives through . Function orden finds the Taylor table’s first nonzero moment.
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 = eWeights and constants match the text, and error ratios when halving approach 4: order 2, checked without knowing the constant.
The Richardson table on central differences, with large and small initial steps:
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 the level-3 column reaches and the table stalls at ; with the first level already reaches and later levels worsen.
Complex step and what breaks it:
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 ; the gradient is handwritten with optional bugs.
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 and the three bugs , and . The bug is subtle (a term of size ) but almost five orders above noise.
- In float32, the correct gradient gives and the one omitting gives : less than the correct one. No threshold separates them.
- The correct gradient’s Taylor test has slope throughout; the gradient omitting starts at 2 (large makes the quadratic term dominate) and falls to between and , toward 1 as linear error takes over.
- At the kink, the correct gradient (under convention ) 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.
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 grow by slightly less than threefold per iteration (768 to 2,096 between and ), expanded-form operations double (44 to 92 between and , 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 only twice and are cheapest but have 1.8% error: is a degree-64 polynomial with enormous high derivatives, so truncation with 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 defaultepsilon(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 betweengrad(x0)andapprox_fprime: an absolute error. Withdirection="random"it compares in one random direction.torch.autograd.gradcheck(fn, inputs)compares the Jacobian frombackwardagainst central differences, with defaultseps=1e-6,atol=1e-5andrtol=1e-3, accepting if for every entry. It warns when inputs are not double precision.sympy.diff,sympy.cseandsympy.lambdify(..., cse=True)differentiate, share subexpressions and generate a NumPy function, as in the lab.
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 () than for the incorrect one (): it measures the scale of , 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 instead of ) and one precision-related (compute sigmoid in float32 within float64 backward). This cell requires PyTorch and runs locally.
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}")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 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 () reveal the precision bug too. Defaults avoid false alarms rather than find small bugs; tune them when writing your own backward.
Common mistakes
Exercises
Step 1 of 4. Which expansions give truncation error?
More than one answer may be correct.
backward treats all neurons with the same vectorized code, using central differences in float64 with . All components have relative error between and except three, at , and : two weights and the bias of one neuron. Changing to leaves them at , and . What is most likely?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 , default eps , ; component relative error is , or 0 if both are 0. Do not modify x. Tests check that a correct gradient gives less than and a changed sign, missing factor 2 or missing small term exceeds , also when function scale is or (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.0Connections 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
- Taylor table yields any difference formula; the first nonzero moment gives order and error constant, and Fornberg’s algorithm calculates weights without solving systems.
- Total error forms a V; optimal step is and minimum error : for forward and for central differences.
- Richardson eliminates even central-error terms, permits large starting steps and one level equals the five-point formula.
- gives to machine precision for arbitrarily small if all code is holomorphic:
abs,norm,conj,signand real conversions break it. - A numerical gradient costs 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.