Algorithms · Visualized
Compression: Arithmetic Coding
Compression & Encoding
Shrink data with runs, frequencies, and clever codes.
Arithmetic coding compresses a message by representing it as a single fractional number in [0,1): each symbol narrows the current interval to the symbol's probability-scaled sub-interval. Time: O(n) for a message of length n average, O(n) worst; space: O(1) for encoding state (excluding the probability model).
Big-O: Huffman gives prefix-free optimal codes.
Arithmetic Coding
Compression / EncodingArithmetic coding compresses a message by representing it as a single fractional number in [0,1): each symbol narrows the current interval to the symbol's probability-scaled sub-interval. Unlike Huffman coding, symbols can cost a fractional number of bits, so the code approaches the theoretical entropy limit.
How Arithmetic Coding Works
- Assign each symbol a probability and a sub-interval of [0,1) from its cumulative probability.
- Start with the full interval [0,1).
- For each symbol of the message, narrow the current interval to that symbol's sub-interval, scaled into the current range.
- After all symbols, any value inside the final narrow interval uniquely decodes back to the message.
- Decoding: repeatedly find which symbol's sub-interval contains the encoded value, output it, and narrow the range exactly like the encoder.
Arithmetic Coding Worked Example
Input: {msg: AB, probs: {A: 0.6, B: 0.4}}
Start with [0,1). Symbol 'A' occupies [0,0.6) → interval becomes [0,0.6). Symbol 'B' occupies the upper 40% of the current interval → [0 + 0.6·0.6, 0 + 0.6·1.0) = [0.36, 0.6). Any value in [0.36, 0.6), e.g. 0.5, uniquely represents 'AB'.
| symbol | probability | sub-interval | |
|---|---|---|---|
| A | A | 0.6 | [0.0, 0.6) |
| B | B | 0.4 | [0.6, 1.0) |
def arithmetic_encode(msg, probs):
lo, hi = 0.0, 1.0
cum = {}
acc = 0.0
for ch, p in probs.items():
cum[ch] = (acc, acc + p)
acc += p
for ch in msg:
sl, sh = cum[ch]
span = hi - lo
lo, hi = lo + span * sl, lo + span * sh
return (lo + hi) / 2 # any value in [lo, hi) decodes to msgBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Arithmetic Coding Time & Space Complexity
When to Use Arithmetic Coding
- Image and video compression (JPEG2000, H.264 CABAC).
- General-purpose compressors (bzip2, the PAQ family).
- Any scenario needing near-entropy-optimal compression.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.