Numerical stability
Suppose two latent classes have joint probabilities with an examinee’s response pattern whose logarithms are $-1000$ and $-1001$. Both exponentials round to zero in double precision, although the first probability is $e$ times the second. The ratio of their joint probabilities disappears if those rounded values are used. Algebraically equivalent expressions can avoid this loss. The calculations collected here provide a reference for evaluating likelihood terms when direct computation would discard distinctions that matter to the statistical result.
C.1 Logarithm of a sum of exponentials and normalized weights
Let $a_i$ denote the log of the weight assigned to component $i$, with $a_i=-\infty$ for a zero weight. To compute the log of the total weight $W=\sum_i e^{a_i}$, first consider a finite collection with finite maximum $m=\max_i a_i$. Write each weight as a product with a common multiplier, $e^{a_i}=e^m e^{a_i-m}$. Taking the logarithm after factoring the sum gives
\[\log W=\log\!\left(e^m\sum_i e^{a_i-m}\right) =m+\log\sum_i e^{a_i-m}.\]The last expression needs only the logarithm of the common multiplier, which is already $m$. At least one shifted exponential equals one, and none exceeds one. A small term can still round to zero, but the term at the maximum ensures that the shifted sum is at least one. Two cases need attention before taking differences. An empty vector has no maximum to subtract. If every log weight is negative infinity, subtracting the maximum would give an undefined difference. In both cases $W=0$, and logsumexp() returns $-\infty$.
When $W$ is positive and finite, the probability of component $i$ is $p_i=e^{a_i}/W$. The calculation below obtains these probabilities without representing $W$ itself on the ordinary scale. Writing $b_i=a_i-m$ and substituting the expression for $\log W$ into $\log p_i=a_i-\log W$ gives
\[\log p_i=b_i-\log\sum_j e^{b_j}.\]The function normalize_logweights() first forms the vector of shifted log weights. It subtracts logsumexp() of that vector from each $b_i$ and exponentiates the result. Adding a finite constant $c$ to every log weight increases the maximum by the same amount, so $(a_i+c)-(m+c)=b_i$ for every component. The original log total increases by $c$, but the common multiplier $e^c$ cancels from each probability in exact arithmetic. A shift cannot restore differences already lost when the input values were rounded.
For one observed pattern $y$ of test responses and fixed model parameters, let $\pi_i$ be the proportion of examinees in class $i$ and let $f_i(y)$ be the probability of the pattern within that class. The joint probability of class $i$ and pattern $y$ is $\pi_i f_i(y)$. Summing over classes gives the marginal probability of observing $y$. Dividing the joint probability by that sum gives the posterior probability that an examinee with this pattern belongs to class $i$. A class that assigns zero probability to the pattern receives posterior probability zero as long as another class has positive joint probability. If every joint probability vanishes, the model gives the observed pattern probability zero. Dividing the joint probabilities by their total would then require $0/0$.
Take three finite log weights $(-1000,-1001,-1005)$. Dividing each weight by the first subtracts $-1000$ from its logarithm. The relative weights are $(1,e^{-1},e^{-5})$, so all three enter the normalizing sum. The executed example gives the third component zero weight by setting its log weight to $-\infty$. From the book directory, start a fresh R session and follow code/examples/appendix-stability.R. The source call loads the stability functions used below. Continue in this session throughout the appendix. The vector a contains the log weights for this second case.
1
2
3
4
5
source("code/lib/stability.R")
a <- c(-1000,-1001,-Inf)
print(data.frame(log_unnormalized_weight=a,shifted=a-max(a),raw_weight=exp(a),
probability=normalize_logweights(a),
shifted_probability=normalize_logweights(a+735)))
1
2
3
4
log_unnormalized_weight shifted raw_weight probability shifted_probability
1 -1000 0 0 0.7310586 0.7310586
2 -1001 -1 0 0.2689414 0.2689414
3 -Inf -Inf 0 0.0000000 0.0000000
The log_unnormalized_weight column identifies the inputs. Subtracting their maximum gives the shifted values $0,-1,-\infty$. All three entries of raw_weight print as zero. The first two are positive weights too small to represent directly. The third is exactly zero. The relative weights now sum to $1+e^{-1}$, so the first probability is $1/(1+e^{-1})=0.7310586$ to the printed precision. The second component receives the remaining 0.2689414. The shifted_probability column repeats the calculation after adding 735 to a. The finite log weights are now $-265$ and $-266$, still one unit apart.
1
2
print(c(log_total=logsumexp(a),empty=logsumexp(numeric()),
impossible=logsumexp(c(-Inf,-Inf))))
1
2
log_total empty impossible
-999.6867 -Inf -Inf
For a, adding its maximum back to the log of the relative sum gives $-1000+\log(1+e^{-1})$, printed as log_total. The empty and impossible entries give log totals for a vector with no components and a vector with two zero weights. The next call attempts to normalize the two zero weights. The error handler returns the message to print() so the session can continue.
1
print(tryCatch(normalize_logweights(c(-Inf,-Inf)),error=conditionMessage))
1
[1] "Log weights must exclude NA and positive infinity and include a finite value"
Both functions check for missing log weights before looking for a maximum. An entry of NA or NaN stops either calculation, even if another entry is positive infinity. If an otherwise valid vector contains Inf, logsumexp() returns Inf. The normalization function rejects such a vector because subtracting this maximum from itself would give an undefined difference. It also rejects an empty vector or one whose entries are all negative infinity. The two entries of -Inf in the last call trigger the printed message. With zero total weight, the model supplies no posterior probabilities for the observed pattern. The matrixStats package provides a log-sum-exp calculation for vectors.
C.2 Log probabilities, tail probabilities, and stable elementary functions
When a model predicts success with a probability that rounds to one, how much does an observed failure contribute to the log likelihood? For a finite linear predictor $\eta$, the logistic model gives $p_\eta=1/(1+e^{-\eta})$ with $0<p_\eta<1$. Thus $\eta$ is the log odds of success at the specified covariates and any conditioned-on effects. Evaluating the log probabilities directly avoids subtracting a rounded success probability from one. Put $h=\max(\eta,0)$. Factoring $e^h$ from $1+e^\eta$ leaves $1+e^{-\vert \eta\vert }$, since the larger of the two exponents becomes zero. The function log1pexp(), loaded in Section C.1, therefore evaluates
Taking logs of $p_\eta$ and of $1-p_\eta=1/(1+e^\eta)$ gives $-L(-\eta)$ for success and $-L(\eta)$ for failure. With $y$ successes in $m$ independent trials at this linear predictor, the log probability is $\log\binom{m}{y}-yL(-\eta)-(m-y)L(\eta)$. For large positive $\eta$, each failure contributes approximately $-\eta$. For large negative $\eta$, each success contributes approximately $\eta$. Both contributions remain available even when computing the rarer probability by subtraction would give zero.
Two elementary functions retain differences that direct arithmetic can lose. For $x$ near zero, adding $x$ to one can round away part or all of $x$ before the logarithm is taken. The function log1p(x) evaluates $\log(1+x)$ accurately near zero. In $L(\eta)$ its argument is $e^{-\vert \eta\vert }$. In $e^x-1$, the exponential can round to one before the subtraction takes place. Even when the difference survives, it can be comparable in size to the rounding error. The function expm1(x) evaluates $e^x-1$ directly. Both functions have derivative one at zero, so for small $x$ their values are close to $x$. This matters when the small difference itself is the quantity whose logarithm is needed.
Suppose two positive probabilities have log values $a>b$. Their difference is positive. Factoring out the larger probability gives a formula in which the argument of expm1() is the gap between the logs.
Define logdiffexp() for pairs of log values in the same positions of two vectors. The logical vector different selects the entries for which the difference is strictly positive.
1
2
3
4
5
6
logdiffexp <- function(a,b) {
stopifnot(length(a)==length(b),all(!is.na(a)&!is.na(b)),all(a>=b),all(a<Inf))
out <- rep(-Inf,length(a)); different <- a>b
out[different] <- a[different]+log(-expm1(b[different]-a[different]))
out
}
When two inputs satisfying the checks above are equal, their difference on the probability scale is zero, so their output remains -Inf. This includes a pair of negative infinities. If $a$ is finite and $b=-\infty$, the smaller probability is zero and the result is $a$. The checks reject unequal vector lengths, missing values, reversed pairs and positive infinity as the upper log value. When $b$ is close to $a$, expm1() preserves the small difference needed inside the logarithm. For widely separated inputs, expm1(b-a) can round to $-1$, losing a small correction to $a$.
How much standard normal probability lies between 9 and 9.001? Let $Z$ be standard normal, $\Phi$ its cumulative distribution function, $\phi$ its density and $S(x)=P(Z>x)$ its upper-tail probability. Both lower-tail probabilities round to one in double precision. The upper-tail probabilities decrease as the boundary increases and distinguish these bounds. With lower.tail=FALSE and log.p=TRUE, the first pnorm() call gives $a=\log S(9)$ and the second gives $b=\log S(9.001)$. These are the inputs in the order required by logdiffexp(). For an interval far into the left tail, the lower-tail log probabilities would serve the same purpose, with the value at the higher boundary first.
The same calculation reports the upper-tail inverse Mills ratio $\phi(x)/S(x)$, the standard normal hazard function. It divides the density at the boundary by the probability above that boundary; its reciprocal $S(x)/\phi(x)$ is the upper-tail Mills ratio. Some econometric texts instead call $\phi(x)/\Phi(x)$ the inverse Mills ratio. The denominator and tail qualifier specify the convention used here.
1
2
3
4
5
6
bounds <- c(9,9.001)
log_interval <- logdiffexp(pnorm(bounds[1],lower.tail=FALSE,log.p=TRUE),
pnorm(bounds[2],lower.tail=FALSE,log.p=TRUE))
print(c(naive_interval=diff(pnorm(bounds)),stable_log_interval=log_interval,
upper_tail_inverse_Mills_ratio=exp(dnorm(9,log=TRUE)-
pnorm(9,lower.tail=FALSE,log.p=TRUE))))
1
2
naive_interval stable_log_interval upper_tail_inverse_Mills_ratio
0.000000 -48.331191 9.108523
The zero in naive_interval comes from subtracting the two rounded values of $\Phi$. The result in stable_log_interval is $\log\lbrace S(9)-S(9.001)\rbrace \approx-48.331191$. Exponentiating this value recovers the small positive interval probability. The last expression subtracts $\log S(9)$ from the log density returned by dnorm() and exponentiates. Thus upper_tail_inverse_Mills_ratio evaluates the defined ratio at the lower boundary, $\phi(9)/S(9)\approx9.108523$. Its denominator includes all values above 9.
The next table compares exp(x)-1 with expm1(x) and log(1+x) with log1p(x) at three inputs near zero to locate the loss of precision.
1
2
3
x <- c(-1e-16,1e-16,1e-9)
print(data.frame(x=x,exp_minus_one=exp(x)-1,expm1=expm1(x),
log_one_plus=log(1+x),log1p=log1p(x)))
1
2
3
4
x exp_minus_one expm1 log_one_plus log1p
1 -1e-16 -1.110223e-16 -1e-16 -1.110223e-16 -1e-16
2 1e-16 0.000000e+00 1e-16 0.000000e+00 1e-16
3 1e-09 1.000000e-09 1e-09 1.000000e-09 1e-09
At $x=10^{-16}$, the two direct expressions return zero, while expm1(x) and log1p(x) both return $10^{-16}$ to the printed precision. At $x=-10^{-16}$, the direct results have the correct sign but their magnitudes are too large. At $10^{-9}$ all four columns agree to the digits shown.
This loss of precision can affect a quantile when a small exponential difference is divided by a small parameter. For a unit-scale generalized Pareto distribution with lower endpoint zero and nonzero shape $k$, the upper-tail probability at $q$ is $(1+kq)^{-1/k}$ for $q\ge0$ and $1+kq>0$. For negative $k$, the upper endpoint is $-1/k$. For a quantile of order $0<p<1$, setting this probability to $1-p$ gives $\log(1+kq)=-k\log(1-p)$, hence
\[q=\frac{\operatorname{expm1}[-k\log(1-p)]}{k}.\]As $k$ tends to zero, $\operatorname{expm1}(t)/t$ tends to one for $t=-k\log(1-p)$. The quantile therefore tends to $-\log(1-p)$. The loop uses this limit at zero shape and sets prob to 0.98 throughout.
1
2
3
4
5
prob <- .98
for (k in c(-1e-9,0,1e-9,.1)) {
q <- if (k==0) -log1p(-prob) else expm1(-k*log1p(-prob))/k
print(c(shape=k,unit_scale_quantile=q,exponential_limit=-log1p(-prob)))
}
1
2
3
4
5
6
7
8
shape unit_scale_quantile exponential_limit
-0.000000001 3.912022998 3.912023005
shape unit_scale_quantile exponential_limit
0.000000 3.912023 3.912023
shape unit_scale_quantile exponential_limit
0.000000001 3.912023013 3.912023005
shape unit_scale_quantile exponential_limit
0.100000 4.787576 3.912023
The shapes $-10^{-9}$ and $10^{-9}$ give quantiles just below and just above the exponential limit of 3.912023005. At shape 0.1, the quantile is 4.787576. A quantile gives a boundary at a specified probability.
Return to the normal interval probability calculated earlier in this section. For an ordinal response, the observed category specifies an interval between two cutpoints on the latent response scale. Its probability is the probability that the latent response falls in that interval. If the latent response is standard normal and its cutpoints are 9 and 9.001, log_interval gives the category’s log probability. To obtain the conditional density of that response given its category, subtract log_interval from the normal log density inside the interval and exponentiate.
The same narrow category illustrates a numerical problem for a randomized quantile residual. For an observed discrete response $y$, let $A=P(Y<y)$ and $B=P(Y\le y)$. The randomized probability integral transform selects $u=A+v(B-A)$ using an independent uniform draw $v$ on $(0,1)$. The randomized quantile residual is $\Phi^{-1}(u)$, putting this cumulative probability on the standard normal scale. At the lowest possible category, $A=0$ is an exact endpoint. If $B>A$, the selected cumulative probability satisfies $A<u<B$ and hence $0<u<1$ in exact arithmetic, even when $A=0$ or $B=1$. The function randomized_quantile_residuals() passes its interpolated value directly to qnorm(). For the interval from 9 to 9.001, passing the rounded lower-tail values $A=B=1$ would yield positive infinity for every draw. The exact category probability is positive. A cumulative probability rounded to zero would likewise give negative infinity. Calculating the small tail probability directly preserves information that the rounded lower-tail probabilities have lost. The base package provides the elementary functions and stats provides the normal probability and quantile functions.
C.3 Cholesky log determinants and triangular solves
Suppose two test scores have a joint normal distribution. The log density of an examinee’s scores depends on the log determinant of their covariance matrix and the squared distance from the mean in units set by that covariance. Let $S$ be a symmetric positive definite covariance matrix. With its default unpivoted factorization, R <- chol(S) returns an upper triangular matrix $R$ with positive diagonal entries and $S=R^\top R$. The default chol() reads only the upper triangle and does not test symmetry. A triangular matrix has determinant equal to the product of its diagonal entries. Since transposition preserves the determinant, $\det S=(\prod_j R_{jj})^2$ and hence
This sum uses the positive diagonal entries directly, even when their product would overflow or underflow.
For the distance term, take an observed residual $r=(1,-0.5)^\top$, the two scores minus their respective means. Use a covariance matrix $\Sigma$ with variances 2 and 1 and covariance 0.3. At each positive scale $c$, compute the Cholesky factor of $S=c\Sigma$ and first solve the lower triangular system $R^\top v=r$. Write $R^{-\top}$ for the inverse of $R^\top$. If the random residual has covariance $S$, then $v=R^{-\top}r$ has covariance $R^{-\top}SR^{-1}=I$. Its components therefore have unit variances and zero covariances. They are also independent when the residual vector is jointly normal. The squared length of the observed $v$ gives the quadratic form in the normal log density,
\[v^\top v=r^\top R^{-1}R^{-\top}r=r^\top S^{-1}r.\]The loop uses forwardsolve() to obtain v and reports its squared length as quadratic. A second solve, backsolve(R,v), gives the vector $x$ satisfying $Rx=v$. Multiplying by $R^\top$ shows that $Sx=r$.
The output residual is the largest absolute component of $Sx-r$, measuring how closely the computed solution satisfies this linear system. The observed score residual $r$ remains fixed. The output condition is the two-norm condition number, the largest singular value of $S$ divided by its smallest. It describes sensitivity of the solve to relative perturbations in the system.
1
2
3
4
5
6
7
8
9
10
Sigma <- matrix(c(2,.3,.3,1),2)
r <- c(1,-.5)
for (scale in c(1e-60,1,1e60)) {
S <- Sigma*scale
R <- chol(S)
v <- forwardsolve(t(R),r)
x <- backsolve(R,v)
print(c(scale=scale,logdet=2*sum(log(diag(R))),quadratic=sum(v^2),
residual=max(abs(S%*%x-r)),condition=kappa(S,exact=TRUE)))
}
1
2
3
4
5
6
scale logdet quadratic residual condition
1.000000e-60 -2.756631e+02 9.424084e+59 2.220446e-16 2.271877e+00
scale logdet quadratic residual condition
1.000000e+00 6.471032e-01 9.424084e-01 1.110223e-16 2.271877e+00
scale logdet quadratic residual condition
1.000000e+60 2.769573e+02 9.424084e-61 1.110223e-16 2.271877e+00
At unit scale the first component of $v$ is $1/\sqrt{2}$. The second equation of $R^\top v=r$ gives $v_2=(-0.5-0.15)/\sqrt{1-0.3^2/2}$. Squaring and adding these components reproduces the middle row’s quadratic value.
At $c=1$ the log determinant is $\log(2-0.3^2)\approx0.64710$ and the quadratic form is 0.94241. In two dimensions $\det(c\Sigma)=c^2\det\Sigma$, so the log determinant changes from its unit-scale value by about $-276.31$ at $10^{-60}$ and $+276.31$ at $10^{60}$. Since $(c\Sigma)^{-1}=\Sigma^{-1}/c$, the quadratic form for the same $r$ is divided by $c$. Both singular values scale by $c$, leaving their ratio, the condition number, at 2.271877. All three absolute solve residuals are at rounding level. Judging the relative error in $x$ from this residual also requires the scale and conditioning of the system.
The same Cholesky factor also generates a vector of test scores with mean $\mu$ and covariance $\Sigma$. At the original scale, write $\Sigma=R^\top R$. For a column $z$ of independent standard normal variables, define $y=\mu+R^\top z$. Its mean is $\mu$, and its covariance is $R^\top I R=\Sigma$. Multiplying by the lower Cholesky factor gives the deviations their desired variances and covariance. To recover the original standardized components from $y$, solve $R^\top v=y-\mu$. Four fixed points with zero mean and identity second moment provide a deterministic check of this covariance transformation.
The loop leaves R at its largest scale, so the next call recomputes the Cholesky factor of Sigma. Let $P$ be the matrix points. Its four rows lie at $\pm\sqrt{2}$ on the two coordinate axes. Opposite rows cancel in the mean. For each coordinate, the two nonzero entries contribute 2 apiece to its sum of squares. No point has both coordinates nonzero, giving $P^\top P/4=I$. Because the points occupy rows, multiplying points %*% R applies the column transformation $z\mapsto R^\top z$ to each point.
1
2
3
4
R <- chol(Sigma)
# Four symmetric standardized points have exactly zero mean and identity second moment.
points <- sqrt(2)*rbind(diag(2),-diag(2))
print(covariance_from_points <- crossprod(points%*%R)/4)
1
2
3
[,1] [,2]
[1,] 2.0 0.3
[2,] 0.3 1.0
For the transformed rows, crossprod() gives $(PR)^\top(PR)$. Division by four assigns each point probability one quarter, so the displayed matrix is their covariance. For the precision matrix, write $\Sigma^{-1}=U^\top U$. The object precision_chol below contains the upper Cholesky factor $U$ of the precision matrix. Solving $Ux=z$ produces $x=U^{-1}z$ with covariance $U^{-1}U^{-\top}=(U^\top U)^{-1}=\Sigma$. The four right-hand sides are now columns.
1
2
precision_chol <- chol(solve(Sigma))
print(covariance_from_precision_chol <- tcrossprod(backsolve(precision_chol,t(points)))/4)
1
2
3
[,1] [,2]
[1,] 2.0 0.3
[2,] 0.3 1.0
With transformed columns in a matrix $X$, tcrossprod() gives $XX^\top$. The diagonal entries again recover variances 2 and 1, and the off-diagonal entries recover covariance 0.3. A linear transformation multiplies volume by the absolute value of its determinant. For multiplication by $R^\top$ this multiplier is $\vert \det R\vert $, and for a solve with $U$ it is $\vert \det U^{-1}\vert =1/\vert \det U\vert $. Both equal $\sqrt{\det\Sigma}$.
The preceding examples use positive definite covariance matrices. Now consider what happens when the two scores have unit variance and correlation one.
1
print(tryCatch(chol(matrix(1,2,2)),error=conditionMessage))
1
[1] "the leading minor of order 2 is not positive"
The two rows coincide. After the first diagonal step of one, the next Cholesky step encounters $1-1^2=0$, which accounts for the error. This covariance is singular. A positive definite covariance whose smallest eigenvalue is tiny relative to its largest still has an inverse. Its large condition number makes the solution sensitive to perturbations in some directions. Adding a positive constant to the diagonal would increase both variances without changing the covariance between scores. If that adjusted matrix replaces the covariance in the likelihood, it changes the response model. The base package provides the Cholesky factorization and both triangular solves.