How computers store numbers

Part 1 — Numbers on a computer

Numerical analysis for biologists

About this lecture

In Why numerical analysis? we met three ways a computation goes wrong: rounding, truncation and instability. This lecture is about the first one: where rounding comes from.

  • A computer stores a real number in 64 bits, in binary. Most decimals (even 0.1) cannot be stored exactly.
  • The numbers it can store are spaced relative to their size: about 16 significant digits, everywhere. That spacing is machine epsilon.
  • There is a largest and a smallest number. Go past them and you get Inf or 0 (overflow / underflow), or NaN.
  • Never test floats with ==; compare with a tolerance.
  • Biology: the likelihood of a long alignment (or of 10 000 reads) underflows to 0. The fix is to work with logs, add probabilities with log-sum-exp, and use log1p/expm1 for small rates.

A biology problem first

A phylogenetics program computes the likelihood of a tree from an alignment of 10 000 sites. Each site contributes a probability between 0.01 and 0.5; the sites are independent, so the likelihood is the product.

set.seed(1)
p <- runif(10000, min = 0.01, max = 0.5)   # per-site likelihoods
prod(p)
# [1] 0
sum(log(p))
# [1] -16177.67
  • The true likelihood is about e^{-16178} \approx 10^{-7026}. Not zero, but smaller than any number R can store.
  • Two trees with likelihood “0” cannot be compared. The log of the same quantity is a perfectly ordinary number.
  • Why does this happen, and where exactly is the limit? That needs a look at how numbers are stored.

A second surprise

0.1 + 0.2 == 0.3
# [1] FALSE

0.1 + 0.2
# [1] 0.3                       # R prints 7 significant digits by default

sprintf("%.20f", c(0.1, 0.2, 0.1 + 0.2, 0.3))
# [1] "0.10000000000000000555" "0.20000000000000001110" "0.30000000000000004441"
# [4] "0.29999999999999998890"
  • None of 0.1, 0.2, 0.3 is stored exactly. The sum lands on a different stored number than 0.3.
  • sprintf with "%.20f" shows more digits than print does; use it to see what is really stored.

Binary integers

Decimal uses powers of 10; binary uses powers of 2, with digits 0 and 1.

13 = 8 + 4 + 1 = 1\cdot 2^3 + 1\cdot 2^2 + 0\cdot 2^1 + 1\cdot 2^0 = 1101_2

Recipe (decimal → binary): divide by 2, write down the remainder, repeat; read the remainders bottom-up.

step quotient remainder
13 / 2 6 1
6 / 2 3 0
3 / 2 1 1
1 / 2 0 1

Bottom-up: 1101_2. Check: 8+4+0+1 = 13.

Binary fractions

After the binary point the places are \tfrac12, \tfrac14, \tfrac18, \dots

0.625 = \tfrac12 + \tfrac18 = 0.101_2

Recipe (fraction → binary): multiply by 2, the integer part is the next bit, keep the fraction, repeat.

0.625:

  • 0.625 \cdot 2 = \mathbf{1}.25
  • 0.25 \cdot 2 = \mathbf{0}.5
  • 0.5 \cdot 2 = \mathbf{1}.0 → stop

0.625 = 0.101_2, exact.

0.1:

  • 0.1 \to \mathbf{0}.2 \to \mathbf{0}.4 \to \mathbf{0}.8 \to \mathbf{1}.6
  • 0.6 \to \mathbf{1}.2 \to \mathbf{0}.4 \to \dots (repeats)

0.1 = 0.0\overline{0011}_2, never stops.

Only fractions with a power of 2 in the denominator (\tfrac12, \tfrac38, \tfrac{5}{16}) end. Like \tfrac13 = 0.333\ldots in decimal, \tfrac1{10} repeats forever in binary, so it must be cut off.

Scientific notation in base 2

Write every nonzero number as

x = \pm\, 1.f \times 2^{e}, \qquad \text{e.g. } 13 = 1.101_2 \times 2^3, \quad 0.625 = 1.01_2 \times 2^{-1}

  • The leading digit is always 1, so it does not need to be stored.
  • Only the sign, the exponent e and the fraction f are stored.
  • A fixed number of bits for f means a fixed number of significant digits, whatever the size of x.

Same idea as 6.02 \times 10^{23}: the digits and the size are kept apart.

The IEEE double: 64 bits

  • 1 sign bit, 11 exponent bits (e from -1022 to 1023), 52 fraction bits.
  • 52 stored + 1 hidden = 53 significant bits \approx 15–16 decimal digits.
  • R’s numeric and Python’s float (and numpy’s float64) are all this format.

Floats are not evenly spaced

A toy system with only 3 fraction bits: 1.f_1f_2f_3 \times 2^e.

  • 8 numbers between each power of 2 and the next. Each time you go up a power of 2, the gap doubles.
  • The relative gap is roughly constant: gap / x is between \tfrac1{16} and \tfrac18.
  • Any real number in between is rounded to the nearest tick.

Machine epsilon

Machine epsilon \varepsilon is the gap between 1 and the next double: \varepsilon = 2^{-52} \approx 2.2 \times 10^{-16}.

.Machine$double.eps
# [1] 2.220446e-16
1 + .Machine$double.eps == 1
# [1] FALSE
1 + .Machine$double.eps / 2 == 1
# [1] TRUE                   # rounded back down to 1
  • .Machine lists the limits of the number system on your computer.
  • Rounding x to the nearest double has relative error at most \varepsilon/2 \approx 1.1 \times 10^{-16}.
  • That is why doubles are good to “about 16 significant digits”.

The gap grows with the number

  • Near x, the gap to the next double is about \varepsilon\,|x|. Exactly: 2^{\lfloor \log_2 |x| \rfloor - 52}.
  • Near 1000: gap 2^{9-52} = 2^{-43} \approx 1.1\times10^{-13}. Near 2^{53} \approx 9\times10^{15}: gap = 2.
  • Relative precision is fixed; absolute precision depends on the size of x.

Every operation rounds

IEEE rule: the result of +, -, \times, /, \sqrt{\ } is the exact result, rounded to the nearest double.

0.1 + 0.2:

  • stored 0.1 + stored 0.2 = 0.3000000000000000166\ldots (exact sum of two stored numbers)
  • nearest double: 0.30000000000000004441
  • stored 0.3: 0.29999999999999998890, one gap (2^{-54} \approx 5.6\times10^{-17}) below
(0.1 + 0.2) - 0.3
# [1] 5.551115e-17

Each step adds a relative error of up to \varepsilon/2. Over millions of steps these errors can add up, or (worse) be magnified. That is Error, conditioning and stability.

Never test floats with ==

x <- seq(0, 1, by = 0.1)
which(x == 0.3)
# integer(0)                                  # not found!
which(abs(x - 0.3) < 1e-9)
# [1] 4

all.equal(0.1 + 0.2, 0.3)
# [1] TRUE
all.equal(1, 1.1)
# [1] "Mean relative difference: 0.1"         # not FALSE!
isTRUE(all.equal(1, 1.1))
# [1] FALSE
  • Compare with a tolerance: |a - b| \le \text{tol} \cdot \max(|a|, |b|) (relative), or |a-b| \le \text{tol} (absolute, near 0).
  • all.equal uses a relative tolerance of 1.5\times10^{-8}. In an if, wrap it in isTRUE().

Subtraction can lose digits

(1 + 1e-15) - 1
# [1] 1.110223e-15             # should be 1e-15: 11% wrong
  • 1 + 10^{-15} is rounded to the nearest double near 1 (gap 2.2\times10^{-16}), so only about one significant digit of 10^{-15} survives.
  • The subtraction itself is exact; it just exposes the earlier rounding.
  • This is catastrophic cancellation: the topic of Error, conditioning and stability (e.g. the variance of genomic positions near 2.4\times10^8).

Integers

R has a separate integer type (32 bits, written 5L); plain 5 is a double.

.Machine$integer.max                       # 2^31 - 1
# [1] 2147483647
len <- c(248956422L, 242193529L, 198295559L, 190214555L, 181538259L,
         170805979L, 159345973L, 145138636L, 138394717L, 133797422L,
         135086622L, 133275309L, 114364328L)     # chr1-13, GRCh38
cumsum(len)[11:13]
# [1] 1943767673 2077042982         NA
# Warning message: integer overflow in 'cumsum'; use 'cumsum(as.numeric(.))'
2^53 + 1 == 2^53
# [1] TRUE
  • The human genome (3.1 × 10⁹ bp) does not fit in a 32-bit integer. Integer overflow gives NA.
  • Doubles store every whole number exactly up to 2^{53} \approx 9\times10^{15}. Above that, the gap is 2 or more.

The range of doubles

.Machine$double.xmax      # largest double
# [1] 1.797693e+308
.Machine$double.xmin      # smallest normal double
# [1] 2.225074e-308
2^-1074                   # smallest subnormal
# [1] 4.940656e-324

Below 2.2\times10^{-308}, subnormal numbers fill the gap to zero, with fewer and fewer significant digits.

Overflow and underflow

1e308 * 10                # overflow
# [1] Inf
exp(709); exp(710)
# [1] 8.218407e+307
# [1] Inf
2^-1075                   # underflow
# [1] 0
exp(-745); exp(-746)
# [1] 4.940656e-324
# [1] 0
  • Overflow → Inf; underflow → 0 (or a subnormal with few digits). No warning in either case.
  • exp overflows for arguments above 709.8 and underflows below about -745. In likelihoods, exp of a log-likelihood is the usual culprit.

Inf, -Inf and NaN

1 / 0;  -1 / 0;  log(0)
# [1] Inf
# [1] -Inf
# [1] -Inf
0 / 0;  Inf - Inf;  Inf * 0
# [1] NaN
# [1] NaN
# [1] NaN
is.finite(c(1, Inf, NaN, NA))
# [1]  TRUE FALSE FALSE FALSE
  • NaN = “not a number”: the result is undefined. Any arithmetic with NaN gives NaN; even NaN == NaN is not TRUE (it is NA in R).
  • In R, NA (missing value) is different from NaN (failed arithmetic); is.na() is TRUE for both, is.nan() only for NaN.
  • Check: stopifnot(all(is.finite(x))) after a long computation.

Try it: inspect a double

Back to the likelihood

  • Each site multiplies the likelihood by about 0.1–0.3, so it loses about 0.7 decimal orders per site.
  • After 470 sites the product is below the smallest subnormal and becomes exactly 0.
  • The sum of the logs is the same information, as an ordinary number of size 10^{4}.

Fix 1: work with log-likelihoods

\log L = \log \prod_i p_i = \sum_i \log p_i

loglik <- sum(log(p))                       # -16177.67
dbinom(3, size = 10, prob = 0.2, log = TRUE) # log of a density, directly
# [1] -1.602827                             # = log(0.2013266)

# compare two trees: likelihood ratio from a difference of logs
loglik_A <- -16177.67;  loglik_B <- -16180.12
exp(loglik_A - loglik_B)                    # L_A / L_B
# [1] 11.58835
  • Products become sums; tiny numbers become moderate negative numbers.
  • Every R density function (dnorm, dbinom, dpois, …) has log = TRUE, which avoids even the single underflow of a very small density.
  • Take exp only of differences of log-likelihoods, which are moderate.

But sometimes we must add probabilities

Logs turn products into sums, but some models need a sum of probabilities:

  • Genotype calling: P(\text{reads}) = \sum_{g \in \{AA, AB, BB\}} P(\text{reads} \mid g)\,P(g)
  • HMMs (gene finding, copy number): the forward algorithm sums over the hidden states at each step.
  • Phylogenetics (Felsenstein’s pruning): at each node, sum over the 4 possible bases.

With 1000 reads, each term P(\text{reads} \mid g) is something like e^{-1000}. We have the logs a_k = \log x_k and need \log \sum_k x_k.

a <- c(-1000, -1001, -1003)         # log P(reads | g) + log P(g)
log(sum(exp(a)))
# [1] -Inf                           # every exp(a) underflowed to 0

Log-sum-exp

Pull out the largest term m = \max_k a_k:

\log \sum_k e^{a_k} = m + \log \sum_k e^{a_k - m}

Now every a_k - m \le 0, and the largest is exactly 0, so e^{0} = 1: no overflow, and the sum is at least 1, so no \log 0.

With a = (-1000, -1001, -1003), m = -1000:

e^{0} + e^{-1} + e^{-3} = 1 + 0.3679 + 0.0498 = 1.4177, \quad \log 1.4177 = 0.3490

\log \sum_k e^{a_k} = -1000 + 0.3490 = -999.651

Log-sum-exp in R

logsumexp <- function(a) {
  m <- max(a)
  m + log(sum(exp(a - m)))
}
a <- c(-1000, -1001, -1003)
logsumexp(a)
# [1] -999.651
exp(a - logsumexp(a))               # posterior P(g | reads)
# [1] 0.70538451 0.25949646 0.03511903
  • Normalising on the log scale gives the posterior probabilities directly; they sum to 1.
  • Base R has no logsumexp; Python has scipy.special.logsumexp.
  • Edge case: if every a_k = -\infty, then m - m is NaN. Production code handles that case separately.

Small rates: log1p and expm1

Mutation rate \mu = 10^{-9} per site per generation. P(\text{at least one mutation}) = 1 - e^{-\mu}.

mu <- 1e-9
print(1 - exp(-mu), digits = 15)
# [1] 9.99999971718069e-10           # wrong from the 8th digit
print(-expm1(-mu), digits = 15)
# [1] 9.999999995e-10                # correct
mu <- 1e-17
1 - exp(-mu);  -expm1(-mu)
# [1] 0
# [1] 1e-17
  • e^{-\mu} is rounded to the nearest double near 1 (gap \varepsilon), and $1 - $ that keeps only the digits that survived.
  • expm1(x) = e^x - 1 and log1p(x) = \log(1+x) are computed without forming 1 + x. Use them when |x| \ll 1.
  • The same holds for \log(1 - p) with small p: use log1p(-p).

Checklist: detecting floating-point trouble

  • Exact zeros or -Inf in a likelihood → underflow. Work on the log scale.
  • Inf or NaN anywhere → overflow or 0/0. Check with is.finite() after each step.
  • == on computed numbers → replace with isTRUE(all.equal(a, b)) or an explicit tolerance.
  • 1 - exp(-x) or log(1 + x) with small x → -expm1(-x), log1p(x).
  • exp() of a log-likelihood → take differences first, or use log-sum-exp.
  • Large whole numbers (coordinates, counts) as R integers → convert with as.numeric() before summing.
  • Doubt about the stored value → sprintf("%.20f", x).

Summary

  • A double is \pm 1.f \times 2^e in 64 bits: 53 significant bits, about 16 decimal digits, range about 10^{-308} to 10^{308}.
  • Most decimals (0.1) are not stored exactly. Every operation rounds to the nearest double, with relative error at most \varepsilon/2, \varepsilon = 2.2\times10^{-16}.
  • The gap between doubles near x is about \varepsilon |x|: relative precision is constant.
  • Compare floats with a tolerance (isTRUE(all.equal())), never ==.
  • Doubles hold whole numbers exactly up to 2^{53}; R integers only to 2^{31}-1.
  • Overflow gives Inf, underflow gives 0, undefined gives NaN, all silently.
  • Likelihoods: sum log-probabilities, add probabilities with log-sum-exp, and use log1p/expm1 for small rates.

Next: error-conditioning, where we measure errors and see when they grow.