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 , spending about bits per symbol even when that is a fraction of a bit. The total length is within 2 bits of the ideal .
The idea: nested intervals
Split 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 , and any number inside it identifies the message. A binary fraction with about bits always fits.
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 is the product of the probabilities, so 6 bits identify the message abac.
Finding the shortest binary number
Choose the shortest binary fraction such that the whole dyadic interval lies inside the message interval. Then any continuation of the bits still decodes correctly, which makes the code prefix-free.
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:
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 . 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.Fractionarithmetic 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 , , ? About how many bits are needed?
Answer
Width 0.03; about 5 to 7 bits.
Solution
and . The code uses at most bits.
Exercise 2: Why not Huffman?
For a source with , 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 bits, and arithmetic coding is within 2 bits of it for the whole message.
Exercise 3: Encode with fractions (code)
Encode "cab" with , , using the encode function from the lesson.
Answer
11010, 5 bits for a message of probability .
Solution
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…
- a binary fraction inside an interval of width P(message)
- a sequence of fixed-length codewords
- a dictionary index
- a Huffman tree
Compared with Huffman coding, arithmetic coding is better because…
- it can spend fractional bits per symbol
- it is always faster
- it needs no model
- it is lossy
Adaptive models fit arithmetic coding well because…
- the probabilities can change after every symbol at no extra cost
- they need no decoder
- they make the code prefix-free
- they avoid integer arithmetic