TExcelTAD
Home › Information Theory › Arithmetic Coding

Arithmetic Coding

Huffman coding spends a whole number of bits on every symbol, which wastes up to a bit per symbol on skewed sources. Arithmetic coding removes that restriction: it encodes the whole message as one number in [0,1)[0, 1), spending about log⁡21P(x)\log_2 \frac{1}{P(x)} bits per symbol even when that is a fraction of a bit. The total length is within 2 bits of the ideal log⁡21P(message)\log_2 \frac{1}{P(\text{message})}.

The idea: nested intervals

Split [0,1)[0, 1) into sub-intervals, one per symbol, with widths equal to the probabilities. To encode a symbol, zoom into its sub-interval and split that again for the next symbol. After the whole message, the interval has width P(message)P(\text{message}), and any number inside it identifies the message. A binary fraction with about log⁡21P(message)+1\log_2 \frac{1}{P(\text{message})} + 1 bits always fits.

python · try it yourself
from fractions import Fraction as F

probs = {"a": F(1, 2), "b": F(1, 4), "c": F(1, 4)}
cum, c = {}, F(0)
for s, p in probs.items():
    cum[s] = c; c += p

low, width = F(0), F(1)
for s in "abac":
    low, width = low + width * cum[s], width * probs[s]
    print(f"after '{s}': [{float(low):.6f}, {float(low + width):.6f})  width {width}")
after 'a': [0.000000, 0.500000)  width 1/2
after 'b': [0.250000, 0.375000)  width 1/8
after 'a': [0.250000, 0.312500)  width 1/16
after 'c': [0.296875, 0.312500)  width 1/64

The final width 164\frac{1}{64} is the product of the probabilities, so 6 bits identify the message abac.

Finding the shortest binary number

Choose the shortest binary fraction 0.b1b2…bk0.b_1b_2\dots b_k such that the whole dyadic interval [0.b1…bk,0.b1…bk+2−k)[0.b_1\dots b_k, 0.b_1\dots b_k + 2^{-k}) lies inside the message interval. Then any continuation of the bits still decodes correctly, which makes the code prefix-free.

python · try it yourself
from fractions import Fraction as F
import math

def encode(msg, probs):
    cum, c = {}, F(0)
    for s, p in probs.items():
        cum[s] = c; c += p
    low, width = F(0), F(1)
    for s in msg:
        low, width = low + width * cum[s], width * probs[s]
    k = 1
    while True:
        v = math.ceil(low * 2**k)                       # smallest k-bit number >= low
        if F(v + 1, 2**k) <= low + width:
            return format(v, f"0{k}b"), width
        k += 1

def decode(bits, n, probs):
    x = F(int(bits, 2), 2**len(bits))
    out, low, width = "", F(0), F(1)
    for _ in range(n):
        c = F(0)
        for s, p in probs.items():
            if low + width * (c + p) > x:
                out += s; low, width = low + width * c, width * p; break
            c += p
    return out

probs = {"a": F(9, 10), "b": F(1, 20), "c": F(1, 20)}
msg = "aaaaabaaaaaaaaacaaaa"
bits, width = encode(msg, probs)
print("message length:", len(msg), " code bits:", len(bits), f" ideal: {-math.log2(width):.2f}")
print("decoded correctly:", decode(bits, len(msg), probs) == msg)
message length: 20  code bits: 13  ideal: 11.38
decoded correctly: True

A Huffman code needs at least 1 bit per symbol, so 20 bits for this message; arithmetic coding needs 13, within 2 bits of the ideal 11.38.

Practical arithmetic coders

Exact fractions grow without bound. Real coders use fixed-width integers (for example 32 bits) for the interval, output leading bits as soon as they are settled, and rescale. When the interval straddles the midpoint and shrinks, they count "pending" bits to emit later. The version below uses symbol counts as the model:

python · try it yourself
import numpy as np

class ArithmeticCoder:
    BITS = 32; FULL = (1 << 32) - 1; HALF = 1 << 31; QUARTER = 1 << 30

    def __init__(self, counts):
        self.cum = np.concatenate([[0], np.cumsum(counts)]).astype(np.int64).tolist()
        self.total = self.cum[-1]

    def encode(self, symbols):
        low, high, pending, out = 0, self.FULL, 0, []
        def emit(bit):
            nonlocal pending
            out.append(bit); out.extend([1 - bit] * pending); pending = 0
        for s in symbols:
            r = high - low + 1
            high = low + r * self.cum[s + 1] // self.total - 1
            low = low + r * self.cum[s] // self.total
            while True:
                if high < self.HALF: emit(0)
                elif low >= self.HALF: emit(1); low -= self.HALF; high -= self.HALF
                elif low >= self.QUARTER and high < 3 * self.QUARTER:
                    pending += 1; low -= self.QUARTER; high -= self.QUARTER
                else: break
                low, high = 2 * low, 2 * high + 1
        pending += 1
        emit(0 if low < self.QUARTER else 1)
        return out

    def decode(self, bits, n):
        bits = bits + [0] * self.BITS
        low, high, value, pos, out = 0, self.FULL, 0, 0, []
        for _ in range(self.BITS):
            value = 2 * value + bits[pos]; pos += 1
        for _ in range(n):
            r = high - low + 1
            target = ((value - low + 1) * self.total - 1) // r
            s = next(i for i in range(len(self.cum) - 1) if self.cum[i + 1] > target)
            out.append(s)
            high = low + r * self.cum[s + 1] // self.total - 1
            low = low + r * self.cum[s] // self.total
            while True:
                if high < self.HALF: pass
                elif low >= self.HALF: low -= self.HALF; high -= self.HALF; value -= self.HALF
                elif low >= self.QUARTER and high < 3 * self.QUARTER:
                    low -= self.QUARTER; high -= self.QUARTER; value -= self.QUARTER
                else: break
                low, high = 2 * low, 2 * high + 1
                value = 2 * value + bits[pos]; pos += 1
        return out

rng = np.random.default_rng(0)
P = np.array([0.9, 0.05, 0.03, 0.02])
msg = rng.choice(4, size=20_000, p=P).tolist()
coder = ArithmeticCoder(np.round(P * 1000).astype(int))
bits = coder.encode(msg)
print("decoded correctly:", coder.decode(bits, len(msg)) == msg)
ideal = -np.sum(np.log2(P[msg]))                  # log2 1/P(message) under the model
print(f"arithmetic: {len(bits)} bits,  ideal log2 1/P(message): {ideal:.1f} bits")
print(f"per symbol: {len(bits) / len(msg):.4f},  entropy {-np.sum(P * np.log2(P)):.4f},  Huffman 1.15")
decoded correctly: True
arithmetic: 12190 bits,  ideal log2 1/P(message): 12188.9 bits
per symbol: 0.6095,  entropy 0.6175,  Huffman 1.15

The 20,000 symbols cost only about 1 bit more than the ideal log⁡21P(message)\log_2 \frac{1}{P(\text{message})}. The per-symbol figure is slightly below the entropy because this particular sample happens to contain a few fewer rare symbols than average; on average over many messages it is at the entropy.

Separating model and coder

The coder takes whatever probabilities the model supplies, symbol by symbol, and these may change after every symbol. An adaptive model that updates counts as it goes, or a context model that predicts from previous symbols, plugs in without changing the coder. That is why modern compressors (CABAC in H.264/H.265 video, LZMA's range coder, neural compressors) use arithmetic coding: all the intelligence goes into the model (What Compression Can and Cannot Do).

In software

  • Range coders (LZMA, Zstandard's FSE/ANS family) are fast relatives of arithmetic coding; asymmetric numeral systems (ANS) reach the same compression with table lookups.
  • Exact fractions.Fraction arithmetic is fine for teaching and short messages, but it grows quadratically slower; use integer coders for real data.

Exercises

Exercise 1: Interval width

What is the width of the final interval when encoding bca with P(a)=0.5P(a) = 0.5, P(b)=0.3P(b) = 0.3, P(c)=0.2P(c) = 0.2? About how many bits are needed?

Answer

Width 0.03; about 5 to 7 bits.

Solution

0.3×0.2×0.5=0.030.3 \times 0.2 \times 0.5 = 0.03 and log⁡210.03=5.06\log_2 \frac{1}{0.03} = 5.06. The code uses at most ⌈5.06⌉+1=7\lceil 5.06 \rceil + 1 = 7 bits.

Exercise 2: Why not Huffman?

For a source with P(a)=0.999P(a) = 0.999, how many bits per symbol does Huffman need, and how many does arithmetic coding need on long messages?

Answer

Huffman needs at least 1; arithmetic coding about 0.0114.

Solution

The entropy is H2(0.001)≈0.0114H_2(0.001) \approx 0.0114 bits, and arithmetic coding is within 2 bits of it for the whole message.

Exercise 3: Encode with fractions (code)

Encode "cab" with P(a)=12P(a) = \frac{1}{2}, P(b)=14P(b) = \frac{1}{4}, P(c)=14P(c) = \frac{1}{4} using the encode function from the lesson.

Answer

11010, 5 bits for a message of probability 132\frac{1}{32}.

Solution
python · try it yourself
from fractions import Fraction as F
import math

def encode(msg, probs):
    cum, c = {}, F(0)
    for s, p in probs.items():
        cum[s] = c; c += p
    low, width = F(0), F(1)
    for s in msg:
        low, width = low + width * cum[s], width * probs[s]
    k = 1
    while True:
        v = math.ceil(low * 2**k)
        if F(v + 1, 2**k) <= low + width:
            return format(v, f"0{k}b"), width
        k += 1

print(encode("cab", {"a": F(1, 2), "b": F(1, 4), "c": F(1, 4)}))
('11010', Fraction(1, 32))

For dyadic probabilities the interval is itself a dyadic interval, so the bits are exactly the Huffman codewords 11, 0, 10 in a row.

Test yourself

Arithmetic coding encodes a message as…

  1. a binary fraction inside an interval of width P(message)
  2. a sequence of fixed-length codewords
  3. a dictionary index
  4. a Huffman tree

Compared with Huffman coding, arithmetic coding is better because…

  1. it can spend fractional bits per symbol
  2. it is always faster
  3. it needs no model
  4. it is lossy

Adaptive models fit arithmetic coding well because…

  1. the probabilities can change after every symbol at no extra cost
  2. they need no decoder
  3. they make the code prefix-free
  4. they avoid integer arithmetic