Skip to content

Floating point, overflow and the log-sum-exp trick

Computers keep a fixed number of digits. See where that bites - cancellation, overflow, underflow - and the standard fixes - working in logs, subtracting the maximum before exponentiating, and choosing the precision on purpose.

Advanced ~13 min7 steps

What runs in CodeSplash

You will be able to

  • Say roughly how many significant digits float64, float32 and bfloat16 keep, and what machine epsilon is
  • Recognize catastrophic cancellation, overflow and underflow in a calculation
  • Compute log-sum-exp and softmax stably, and explain why likelihoods are summed in logs

Read first

01

A fixed number of digits

Read

A floating-pointFloating-point numberA number stored as a sign, digits and a power of two. Float64 keeps about 16 significant digits, float32 about 7. number stores a sign, a fixed number of binary digits and a power of two.

TypeBitsSignificant digitsLargest value
float6464about 16about 1030810^{308}
float3232about 7about 3×10383 \times 10^{38}
bfloat1616about 3about 3×10383 \times 10^{38}
float1616about 365,504

Machine epsilonMachine epsilonThe gap between 1 and the next representable number: the relative rounding error of one floating-point step. is the gap between 1 and the next number: 2−52≈2.2×10−162^{-52} \approx 2.2 \times 10^{-16} in float64 and 2−23≈1.2×10−72^{-23} \approx 1.2 \times 10^{-7} in float32. Every arithmetic step can add a relative error of that size.

02

Cancellation

Read

Subtracting two nearly equal numbers keeps their difference but not their accuracy. The digits they shared cancel, and what is left is mostly rounding error.

The textbook variance formula x2‾−xˉ2\overline{x^2} - \bar{x}^2 does exactly that when values are large and close together, such as timestamps or sensor readings around 10910^{9}: in float32 it can even come out negative. The two-pass formula, subtract the mean first and then square, avoids it. Centering data before fitting helps for the same reason.

03

Overflow and underflow

Read

e1000e^{1000} is larger than any float64, so it becomes infinity (overflow). e−1000e^{-1000} is smaller than the tiniest float64, so it becomes 0 (underflow).

Both show up in ordinary models. A softmax over scores in the hundreds overflows. The likelihood of 10,000 rows is a product of 10,000 probabilities and underflows to 0, at which point every model looks equally impossible.

The fix for products is to work in logs: sum log-probabilities instead of multiplying probabilities. Hidden Markov models and every maximum-likelihood fit in CodeSplash do this.

04

Log-sum-exp

Read

Logs turn products into sums, but some formulas need the log of a sum of exponentials, such as a softmax denominator or a mixture likelihood. Let m=max⁡ixim = \max_i x_i. Then

log⁡∑iexi=m+log⁡∑iexi−m.\log \sum_i e^{x_i} = m + \log \sum_i e^{x_i - m}.

Every exponent is now at most 0, so nothing overflows, and the largest term is exactly e0=1e^0 = 1, so the sum can't underflow to 0. That is the log-sum-expLog-sum-explog Σ exp(xᵢ), computed as m + log Σ exp(xᵢ − m) with m the largest xᵢ, so nothing overflows. trick. The same shift gives a stable softmaxSoftmaxTurns a vector of scores into probabilities: exponentiate each, divide by the total. Subtracting the max first keeps it stable.: subtract the maximum score before exponentiating.

Python
import numpy as np

x = np.array([1000., 1001., 1002.])
print(np.exp(x) / np.exp(x).sum())          # nan: inf / inf
z = np.exp(x - x.max())
print(z / z.sum())                          # [0.090 0.245 0.665]
print(x.max() + np.log(np.exp(x - x.max()).sum()))   # log-sum-exp
R
x <- c(1000, 1001, 1002)
exp(x) / sum(exp(x))                        # NaN: Inf / Inf
z <- exp(x - max(x))
z / sum(z)                                  # 0.090 0.245 0.665
max(x) + log(sum(exp(x - max(x))))          # log-sum-exp
05

Choosing the precision

Read

Large-scale training often uses mixed precisionMixed precisionTraining with low-precision math for speed and memory while keeping sensitive sums and master weights in higher precision.: bfloat16 or float16 for the heavy matrix products, float32 for weights and sums. It is faster and halves memory, and float16 needs loss scaling so small gradients don't underflow.

CodeSplash makes the opposite trade. Its torch learners train in float64 in both engines, so Python and R results can be compared to many digits. Matching digits is only possible when rounding error is far below the differences being checked.

06

Check: precision

Checkpoint

Check yourself

Roughly how many significant decimal digits does float32 keep?

Show the answer

Answer: b

Float32 has a 24-bit significand, about 7 decimal digits. Float64 keeps about 16.

Check yourself

Readings are all close to 1,000,000,000 with a spread of a few units. Why can x2‾−xˉ2\overline{x^2} - \bar{x}^2 give a wrong, even negative, variance?

Show the answer

Answer: a

Catastrophic cancellation: subtracting nearly equal large numbers. Subtract the mean first, then square.

Check yourself

Using the log-sum-exp trick on x=(1000,2,3)x = (1000, 2, 3): the maximum is 1000. To the nearest whole number, what is log⁡(e1000+e2+e3)\log(e^{1000} + e^{2} + e^{3})?

Show the answer

Answer: 1000

1000+log⁡(1+e−998+e−997)≈10001000 + \log(1 + e^{-998} + e^{-997}) \approx 1000. The smaller terms are negligible, and no step overflowed.

Check yourself

Why does subtracting the maximum score before a softmax not change its result?

Show the answer

Answer: a

exi−m/∑jexj−m=exi/∑jexje^{x_i - m} / \sum_j e^{x_j - m} = e^{x_i} / \sum_j e^{x_j}. Same answer, no overflow.

Check yourself

Why do model fits sum log-likelihoods instead of multiplying likelihoods?

Show the answer

Answer: a

The maximizing parameters are the same either way, but only the log version can be computed for large data.

07

Recap

Recap
  • Float64 keeps about 16 digits, float32 about 7; machine epsilon is the size of one rounding error.
  • Watch for cancellation (subtracting near-equal numbers), overflow and underflow.
  • Work in logs, and subtract the maximum before exponentiating: that is log-sum-exp and stable softmax.

Concepts in this lesson