Skip to content
LeetQuant
QR01 Python for Quantitative Research

QR01 · Python for Quantitative Research · Lesson 4 of 5

Numerical Stability in Research Code

Log-sum-exp, stable softmax and log-likelihoods, mergeable Welford variance for chunked data, condition numbers and why the normal equations square them, and when float32 is and is not safe.

17 min

Objective

The Numerical Computation lesson in the foundations covers how a double is stored, cancellation, compensated summation and comparing floats. This lesson applies those facts to the array code researchers actually write: likelihoods, softmax weights, variances over data too big for memory, regressions and covariance inverses, and the choice between 32- and 64-bit floats. The guiding question is always: what is the largest intermediate value, and what is being subtracted?

Work in logs: log-sum-exp and softmax

Probabilities multiply, and a product of 2,000 normal densities underflows: np.prod(stats.norm.pdf(x)) is 0.0 for 2,000 standard normal draws, while stats.norm.logpdf(x).sum() is a perfectly ordinary −2839.06-2839.06. Store and add log-likelihoods; never multiply likelihoods.

The difficulty comes when log quantities must be added in probability space, as in mixture models, marginal likelihoods and softmax. Factor out the maximum m=max⁡iaim = \max_i a_i:

log⁡∑ieai=m+log⁡∑ieai−m.\log\sum_i e^{a_i} = m + \log\sum_i e^{a_i - m} .

Now the largest term is e0=1e^0 = 1, so nothing overflows, and the sum is at least 1, so the log is safe. Terms that underflow to 0 are exactly those too small to change the answer. The same trick gives a stable softmax, softmax⁡(z)i=ezi−m/∑jezj−m\operatorname{softmax}(z)_i = e^{z_i - m} / \sum_j e^{z_j - m}, and a stable log-softmax, zi−logsumexp⁡(z)z_i - \operatorname{logsumexp}(z), which you should use instead of log(softmax(z)): for z=(0,−800)z = (0, -800), log(softmax(z)) gives [0, -inf] because e−800e^{-800} underflows before the log, while log-softmax gives the exact [0, -800].

SciPy provides these as scipy.special.logsumexp, softmax, log_softmax, expit (the logistic sigmoid) and log_expit. The naive sigmoid 1 / (1 + np.exp(-x)) overflows inside exp for x=−800x = -800 (it happens to return the right limit, 0, with a warning), but its log is −∞-\infty; log_expit(-800.0) returns −800.0-800.0.

Worked example

softmax of large scores

A model outputs scores z=(1000,1001,1002)z = (1000, 1001, 1002). Compute softmax weights and log⁡∑iezi\log\sum_i e^{z_i} in float64.

Show solution
import numpy as np
from scipy.special import logsumexp, softmax

z = np.array([1000.0, 1001.0, 1002.0])
print(np.exp(z) / np.exp(z).sum())      # [nan nan nan]   (exp overflows to inf; inf/inf)

def stable_softmax(z):
    e = np.exp(z - z.max())
    return e / e.sum()

print(stable_softmax(z).round(6))       # [0.090031 0.244728 0.665241]
print(softmax(z).round(6))              # [0.090031 0.244728 0.665241]
print(logsumexp(z))                     # 1002.4076059644444

e1000e^{1000} exceeds the largest double (about 1.8×103081.8 \times 10^{308}, i.e. e709.8e^{709.8}), so the naive version becomes ∞/∞=NaN\infty/\infty = \text{NaN}. Softmax is invariant to adding a constant to every score, so subtracting m=1002m = 1002 changes nothing mathematically: the shifted scores are (−2,−1,0)(-2, -1, 0), with weights e−2,e−1,1e^{-2}, e^{-1}, 1 over their sum 1.503211.50321, giving 0.0900,0.2447,0.66520.0900, 0.2447, 0.6652. The log-sum-exp is 1002+log⁡(1+e−1+e−2)=1002+0.40761=1002.407611002 + \log(1 + e^{-1} + e^{-2}) = 1002 + 0.40761 = 1002.40761.

Variance: two-pass, Welford, and merging chunks

The one-pass formula x2‾−xˉ2\overline{x^2} - \bar x^2 subtracts two numbers of size xˉ2\bar x^2 to get something of size σ2\sigma^2, so it loses about log⁡10(xˉ2/σ2)\log_{10}(\bar x^2/\sigma^2) digits. For 100,000 values at level 10910^9 with unit variance, it returned 128.0; the true sample variance was 0.998. np.var is safe because it is two-pass: compute the mean, then average the squared deviations.

Welford's online update (in the Root Finding and Numerical Stability lesson) handles streams one value at a time. Research data usually arrives in chunks (daily files, partitions on different workers), and the parallel version combines summaries (n,xˉ,M2)(n, \bar x, M_2), where M2=∑(x−xˉ)2M_2 = \sum (x - \bar x)^2. For two batches AA and BB with δ=xˉB−xˉA\delta = \bar x_B - \bar x_A:

n=nA+nB,xˉ=xˉA+δ nBn,M2=M2,A+M2,B+δ2 nAnBn.n = n_A + n_B, \qquad \bar x = \bar x_A + \delta\,\frac{n_B}{n}, \qquad M_2 = M_{2,A} + M_{2,B} + \delta^2\,\frac{n_A n_B}{n} .

The correction term is the between-batch sum of squares. Everything is formed from deviations, never from raw squares of the level, so it keeps the stability of the two-pass method.

def merge(a, b):
    """Combine (n, mean, M2) summaries of two batches (Chan, Golub and LeVeque)."""
    na, ma, m2a = a
    nb, mb, m2b = b
    n = na + nb
    d = mb - ma
    return n, ma + d * nb / n, m2a + m2b + d * d * na * nb / n

def summary(chunk):
    return len(chunk), chunk.mean(), ((chunk - chunk.mean()) ** 2).sum()

rng = np.random.default_rng(3)
x = 1e9 + rng.standard_normal(100_000)
print((x**2).mean() - x.mean() ** 2)          # 128.0   (garbage)

s = summary(x[:30_000])
for chunk in np.array_split(x[30_000:], 7):
    s = merge(s, summary(chunk))
n, mean, m2 = s
print(m2 / n, x.var())                        # 0.99811531717... 0.99811531751...

The merged result agrees with np.var on the whole array to about 9 significant digits (relative difference 3×10−103 \times 10^{-10}), while the naive formula has no correct digits. The same merge rule underlies groupby variance aggregation and distributed statistics.

Conditioning: when the problem itself amplifies error

Stability is a property of an algorithm; conditioning is a property of the problem. The condition number κ(A)=σmax⁡/σmin⁡\kappa(A) = \sigma_{\max}/\sigma_{\min} (ratio of the largest to smallest singular value) bounds how much a relative perturbation in the inputs is amplified in the solution of Ax=bAx = b:

∥Δx∥∥x∥≲κ(A) ∥Δb∥∥b∥.\frac{\lVert \Delta x \rVert}{\lVert x \rVert} \lesssim \kappa(A)\,\frac{\lVert \Delta b \rVert}{\lVert b \rVert} .

With inputs rounded to u≈1.1×10−16u \approx 1.1 \times 10^{-16}, a stable algorithm gives a relative error of about κu\kappa u: you lose roughly log⁡10κ\log_{10}\kappa digits. A stable algorithm cannot rescue an ill-conditioned problem, but an unstable one can make a well-conditioned problem look ill-conditioned.

Two places researchers meet this:

  • Covariance matrices of correlated assets. A 2×22 \times 2 correlation matrix has eigenvalues 1±ρ1 \pm \rho, so κ=(1+ρ)/(1−ρ)\kappa = (1 + \rho)/(1 - \rho): 99 at ρ=0.98\rho = 0.98, 199 at ρ=0.99\rho = 0.99. Floating point is not the problem at that size, but estimation error is amplified by the same factor. With volatilities 20% and 21%, the minimum-variance weights are (1.65,−0.65)(1.65, -0.65) at ρ=0.98\rho = 0.98 and (2.68,−1.68)(2.68, -1.68) at ρ=0.99\rho = 0.99: a one-point change in an estimated correlation moves the position by a full unit of capital. This is why practitioners shrink covariance estimates towards a well-conditioned target.
  • Regression with near-collinear regressors, where the choice of algorithm matters, as the example shows.

The rule "avoid explicit inverses" has a numerical reason as well as a cost one: inv(A) @ b is not backward stable in general, whereas solve is, and its residual can be much larger for ill-conditioned AA.

Worked example

normal equations square the condition number

Fit a degree-7 polynomial on 500 points in [0,1][0, 1] to noise-free data whose true coefficients are all 1. Compare the normal equations (X⊤X)β=X⊤y(X^\top X)\beta = X^\top y (with solve, and with an explicit inverse) against lstsq.

Show solution
n = 500
t = np.linspace(0, 1, n)
X = np.column_stack([t**k for k in range(8)])     # columns 1, t, ..., t^7
y = X @ np.ones(8)                                # exact data, true beta = all ones

print(f"cond(X) = {np.linalg.cond(X):.1e}, cond(X'X) = {np.linalg.cond(X.T @ X):.1e}")
# cond(X) = 1.2e+05, cond(X'X) = 1.5e+10
b_normal = np.linalg.solve(X.T @ X, X.T @ y)
b_inv = np.linalg.inv(X.T @ X) @ (X.T @ y)
b_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]
for name, b in [("normal eq", b_normal), ("inverse", b_inv), ("lstsq", b_lstsq)]:
    print(f"{name:9s} max coef error {np.abs(b - 1).max():.1e}")
# normal eq max coef error 7.3e-07
# inverse   max coef error 1.8e-06
# lstsq     max coef error 4.6e-12

The powers of tt are nearly collinear on [0,1][0, 1], so κ(X)≈1.2×105\kappa(X) \approx 1.2 \times 10^5. Since the singular values of X⊤XX^\top X are the squares of those of XX, κ(X⊤X)=κ(X)2≈1.5×1010\kappa(X^\top X) = \kappa(X)^2 \approx 1.5 \times 10^{10}. The error estimate κu\kappa u predicts about 1.5×1010×1.1×10−16≈2×10−61.5 \times 10^{10} \times 1.1 \times 10^{-16} \approx 2 \times 10^{-6} for the normal equations and 1.2×105×1.1×10−16≈10−111.2 \times 10^5 \times 1.1 \times 10^{-16} \approx 10^{-11} for lstsq, which works on XX directly through an orthogonal factorisation (SVD in NumPy's case). The observed errors match those orders of magnitude: forming X⊤XX^\top X threw away about five digits that the data contained, and the explicit inverse lost a little more.

In practice: use lstsq or a QR-based routine (statsmodels does), standardise regressors, and if κ(X)\kappa(X) is large ask whether the regressors are really distinguishable, because the coefficient standard errors will be huge regardless of the algorithm.

float32 versus float64

float32 has 24 significant bits: ε=2−23≈1.19×10−7\varepsilon = 2^{-23} \approx 1.19 \times 10^{-7}, about 7 decimal digits. It halves memory and bandwidth and is the native type of most GPU work, so it is tempting for large panels. The failure modes are concrete:

  • Integers stop being exact at 224=16,777,2162^{24} = 16{,}777{,}216: np.float32(16_777_216) + np.float32(1) is 16777216.0. Volumes, timestamps and IDs do not belong in float32.
  • Price resolution. The spacing of float32 values near 4,500 is 2−11≈0.000492^{-11} \approx 0.00049, so np.float32(4500.25) + np.float32(0.0001) returns 4500.25 unchanged. An index level stored in float32 cannot represent one-basis-point-of-a-point moves.
  • Accumulation. Summing ten million float32 copies of 0.1 (exact sum about 1,000,000.0149): v.sum() gives 1,000,000.125 because NumPy's sum uses pairwise summation, with error growing like O(log⁡n)O(\log n); but v.cumsum()[-1] gives 1,087,937, an error of almost 9%, because a cumulative sum is necessarily sequential, and once the running total is large, each 0.1 is rounded to the float32 spacing there. Cumulative PnL and cumulative returns in float32 drift.
  • Variances and covariances lose twice the digits in any cancellation, and 7 digits do not leave much.

A reasonable policy: store large raw data in float32 if memory demands it, but accumulate and compute statistics in float64 (v.sum(dtype=np.float64) gives 1,000,000.0149, and astype(np.float64) before cumsum), and keep prices as integer ticks where exactness matters. Also watch for silent downcasting: a float32 array combined with a float32 scalar stays float32.

Knowledge check

For scores z=(−1000,−1001)z = (-1000, -1001), what does the naive np.log(np.exp(z).sum()) return, and what is the correct value of log⁡(e−1000+e−1001)\log(e^{-1000} + e^{-1001})?

Knowledge check

Batch A has n = 2, mean 1, M2 = 0 (values 1, 1). Batch B has n = 2, mean 3, M2 = 0 (values 3, 3). What is M2 of the combined data according to the merge formula?

Knowledge check

A design matrix X has condition number 1e6. Roughly how many significant digits of the regression coefficients can the normal equations (solving X'X β = X'y in float64) be expected to keep?

Knowledge check

A returns panel is stored as float32 to save memory. Which computation is most at risk?

Key takeaways

  • Add log-likelihoods, never multiply likelihoods. Use log-sum-exp, stable softmax and log-softmax (scipy.special) whenever log quantities are summed in probability space.
  • Never compute variance as x2‾−xˉ2\overline{x^2} - \bar x^2. Use two-pass statistics, Welford for streams, and the (n,xˉ,M2)(n, \bar x, M_2) merge rule for chunks.
  • A stable algorithm loses about log⁡10κ\log_{10}\kappa digits. Correlated covariances are ill-conditioned, so estimation error in them is amplified too.
  • Normal equations square κ\kappa; use lstsq/QR. Solve rather than invert.
  • float32 means 7 digits, integers exact only to 2242^{24} and sequential sums that drift; store in float32 if you must, accumulate in float64.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).