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 . 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 :
Now the largest term is , 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, , and a stable log-softmax, , which you should use instead of log(softmax(z)): for , log(softmax(z)) gives [0, -inf] because 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 (it happens to return the right limit, 0, with a warning), but its log is ; log_expit(-800.0) returns .
Worked example
softmax of large scores
A model outputs scores . Compute softmax weights and in float64.
Show solutionHide 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
exceeds the largest double (about , i.e. ), so the naive version becomes . Softmax is invariant to adding a constant to every score, so subtracting changes nothing mathematically: the shifted scores are , with weights over their sum , giving . The log-sum-exp is .
Variance: two-pass, Welford, and merging chunks
The one-pass formula subtracts two numbers of size to get something of size , so it loses about digits. For 100,000 values at level 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 , where . For two batches and with :
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 ), 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 (ratio of the largest to smallest singular value) bounds how much a relative perturbation in the inputs is amplified in the solution of :
With inputs rounded to , a stable algorithm gives a relative error of about : you lose roughly 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 correlation matrix has eigenvalues , so : 99 at , 199 at . 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 at and at : 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 .
Worked example
normal equations square the condition number
Fit a degree-7 polynomial on 500 points in to noise-free data whose true coefficients are all 1. Compare the normal equations (with solve, and with an explicit inverse) against lstsq.
Show solutionHide 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 are nearly collinear on , so . Since the singular values of are the squares of those of , . The error estimate predicts about for the normal equations and for lstsq, which works on directly through an orthogonal factorisation (SVD in NumPy's case). The observed errors match those orders of magnitude: forming 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 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: , 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 :
np.float32(16_777_216) + np.float32(1)is16777216.0. Volumes, timestamps and IDs do not belong in float32. - Price resolution. The spacing of float32 values near 4,500 is , 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'ssumuses pairwise summation, with error growing like ; butv.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 , what does the naive np.log(np.exp(z).sum()) return, and what is the correct value of ?
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 . Use two-pass statistics, Welford for streams, and the merge rule for chunks.
- A stable algorithm loses about digits. Correlated covariances are ill-conditioned, so estimation error in them is amplified too.
- Normal equations square ; use
lstsq/QR. Solve rather than invert. - float32 means 7 digits, integers exact only to 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).