Short answer: Arithmetic coding encodes a message as a single fraction of the unit interval. Each symbol narrows the current interval to the subinterval proportional to the symbol’s probability. The encoder emits bits as soon as they are determined by the shrinking interval, and it uses renormalization to keep the interval in fixed-width integers. The total length approaches the ideal −log₂ of the probability of the message, which can be a fractional number of bits per symbol. Huffman coding cannot, because it assigns each symbol a whole number of bits.
What the problem actually asks
Huffman coding is optimal among prefix codes that give each symbol an integer length. When one symbol has probability 0.99, it still costs at least one bit under Huffman, while its information content is a small fraction of a bit. Arithmetic coding charges each symbol about −log₂ p bits by shrinking an interval, so the cost can be shared across symbols.
The practical difficulty is precision. The interval is stored as integers low and high. When they agree on a leading bit, that bit is emitted and the range is rescaled. A range that straddles one half without agreeing on the next bit needs the underflow, or pending-bit, handling. Omit it and the encoder stalls or emits the wrong bits.
What the algorithm guarantees
With exact arithmetic the final interval identifies the message, and the bit length is within a couple of bits of the ideal codelength. Integer implementations are defined to be exactly decodable when the encoder and decoder use the same probabilities and the same renormalization. Time is linear in the message for a fixed alphabet, plus the cost of maintaining the model. Extra memory is the interval and the model.
The model can be static or adaptive. An adaptive model updates counts after each symbol, and the decoder must update at the same moment. A mismatch in the model is a desynchronized decoder, not a small quality loss. Arithmetic coding is a coder, not a model. It does not discover repetitions. LZ77 can feed it tokens.
The working steps
- Start with the interval [0, 1), represented as integers [low, high).
- For each symbol, partition the current interval in proportion to the cumulative model probabilities and replace the interval by the symbol’s piece.
- While the interval lies entirely in the lower half or entirely in the upper half, emit the corresponding bit and double the interval, subtracting the upper-half offset if needed.
- Handle the straddling case, where the interval lies in the middle half, by tracking pending underflow bits and rescaling around the midpoint.
- The decoder maintains the same interval and a code value, finds which symbol’s subinterval contains the code, and applies the same rescaling.
The near-optimal length assumes the probabilities the coder was given. A bad model produces a long file that was coded perfectly for that bad model. Huffman remains the simpler integer-length coder. The underflow path is part of a correct fixed-precision implementation, not an optional optimization.
Approaches that look simpler and fail
| Approach | Why it fails when the model updates on only one side |
|---|---|
| Adapt the encoder’s counts and leave the decoder’s model static | The intervals diverge. The decoder reads a different symbol and every later symbol is wrong. |
| Emit a Huffman code and call it arithmetic coding | Huffman assigns an integer length to one symbol. Arithmetic coding narrows a shared interval and can spend a fraction of a bit. |
| Ignore the middle-half rescale | The integer range collapses toward zero width while the leading bit is still ambiguous. The coder then has no precision left. |
| Claim a compression ratio without stating the model | The coder approaches the entropy of the model it was given. The model is the rest of the compressor. |
Integer-length symbol codes are Huffman, or the suboptimal Shannon-Fano split. Repeated phrases are LZ77 or LZW. Arithmetic coding is the interval coder that can spend fractional bits.
A working example
This Python fragment narrows an integer interval and rescales when the interval sits in one half or straddles the midpoint. The model gives a, b, and c equal counts. Encoding abc and decoding those bits returns abc.
FULL, HALF, QUARTER = 1 << 16, 1 << 15, 1 << 14
symbols = ("a", "b", "c")
counts = {ch: 1 for ch in symbols}
total = 3
def cumulative(ch):
start = 0
for item in symbols:
if item == ch:
return start, counts[item]
start += counts[item]
def encode(text):
low, high, pending = 0, FULL, 0
bits = []
def emit(bit):
nonlocal pending
bits.append(bit)
while pending:
bits.append(1 - bit)
pending -= 1
for ch in text:
span = high - low
start, width = cumulative(ch)
high = low + span * (start + width) // total
low = low + span * start // total
while True:
if high <= HALF:
emit(0)
elif low >= HALF:
emit(1)
low -= HALF
high -= HALF
elif low >= QUARTER and high <= 3 * QUARTER:
pending += 1
low -= QUARTER
high -= QUARTER
else:
break
low *= 2
high *= 2
pending += 1
emit(0 if low < QUARTER else 1)
return bits
def decode(bits, length):
low, high = 0, FULL
code = 0
index = 0
def read():
nonlocal index
if index >= len(bits):
return 0
bit = bits[index]
index += 1
return bit
for _ in range(16):
code = code * 2 + read()
out = []
for _ in range(length):
span = high - low
value = ((code - low + 1) * total - 1) // span
start = 0
for ch in symbols:
if start <= value < start + counts[ch]:
width = counts[ch]
chosen = ch
break
start += counts[ch]
out.append(chosen)
high = low + span * (start + width) // total
low = low + span * start // total
while True:
if high <= HALF:
pass
elif low >= HALF:
low -= HALF
high -= HALF
code -= HALF
elif low >= QUARTER and high <= 3 * QUARTER:
low -= QUARTER
high -= QUARTER
code -= QUARTER
else:
break
low *= 2
high *= 2
code = code * 2 + read()
return "".join(out)
bits = encode("abc")
assert decode(bits, 3) == "abc"
print(decode(bits, 3))
Where it is used
CABAC in H.264 and H.265, and the arithmetic coder in JPEG 2000, narrow a fraction instead of emitting a whole Huffman codeword. The tag stays inside the current interval. Huffman coding is the simpler coder those video standards still use for some syntax.
When you can drop this algorithm
Drop a fixed-precision arithmetic coder that has no underflow handling. Use a tested implementation or Huffman when integer lengths are acceptable. Keep arithmetic coding when the model probabilities are far from powers of one half and the fractional bit is the point.
Why this stays published
We publish this so a search for arithmetic coding returns the shrinking interval and the model agreement the decoder requires. Arithmetic coding represents a message by a shrinking probability interval, so the encoded length can approach the ideal fractional bit cost of the model.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
