The first two articles turned uncertainty into information. Now we ask: how do potentially fractional information costs become a binary file that can be decoded exactly?
We will allocate code space, derive the entropy bound, encode a whole message, and examine long sequences. All logarithms are base 2. Unless stated otherwise, the alphabet is finite, the probability model is known, and the cost of transmitting that model is excluded.
Prefix codes: how much space does a codeword occupy?
Binary codewords must remain distinguishable when concatenated. In a prefix code, no codeword is a prefix of another. For example, A=0, B=10, C=110, D=111 can be decoded as soon as each codeword ends, without separators.
Imagine all infinite binary strings as a branching tree. Prefix 0 covers half of them; 10 covers one quarter. Each additional specified bit halves the occupied space. A codeword of length li therefore occupies a fraction 2−li. Prefix-free regions cannot overlap, so:
K=i∑2−li≤1
This is Kraft’s inequality. For given integer lengths, it is also sufficient for a binary prefix code to exist. It guarantees that a code can be constructed, not that arbitrary codewords with those lengths will be prefix-free.
Preparing the visual
Lengths allocate space; Kraft limits total capacity
Compare three length assignments: spare capacity, full capacity, and overflow. Every block has width 2 to the negative codeword length. The dashed line marks capacity 1; feasible states also show actual prefix codewords.
{"id":"source-kraft","title":"Lengths allocate space; Kraft limits total capacity","summary":"Compare three length assignments: spare capacity, full capacity, and overflow. Every block has width 2 to the negative codeword length. The dashed line marks capacity 1; feasible states also show actual prefix codewords.","height":850,"html":"<p class=\"eyebrow\" data-i18n=\"eyebrow\"></p><h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p>\n<div class=\"presets\" role=\"group\" data-i18n-label=\"control\"><button data-case=\"0\" data-i18n=\"slack\"></button><button data-case=\"1\" data-i18n=\"full\"></button><button data-case=\"2\" data-i18n=\"over\"></button></div>\n<div class=\"allocation\" role=\"img\" data-i18n-label=\"chart\"><div class=\"capacity\"></div><div id=\"blocks\"></div><div class=\"limit\"><span>1</span></div></div>\n<div class=\"scale\"><span>0</span><span>1.5</span></div>\n<div class=\"lengths\" id=\"lengths\"></div>\n<div class=\"formula\">K = ∑ 2<sup>−lᵢ</sup> = <strong id=\"sum\"></strong> <span id=\"comparison\"></span> 1</div>\n<div class=\"copy-stack\"><p id=\"explanation\" aria-live=\"polite\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"slackExplain\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"fullExplain\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"overExplain\"></p></div>\n<p class=\"note\" data-i18n=\"note\"></p>","css":".intro { margin:8px 0 18px; color:var(--muted); font-size:14px; }\n.control { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-top:18px; }\n.control output { min-width:4em; flex-shrink:0; text-align:center; background:var(--accent-soft); color:var(--accent); padding:2px 8px; border-radius:6px; font-weight:600; }\n.formula { margin-top:18px; padding:14px 0; border-block:1px solid var(--rule); font-size:16px; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }\n.copy-stack { display:grid; margin-top:14px; color:var(--muted); font-size:14px; }\n.copy-stack > * { grid-area:1/1; }\n.copy-stack .reserve { visibility:hidden; }\n.note { margin-top:14px; color:var(--muted); font-size:12px; }\n.metric-pair { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:18px; }\n.metric-pair > div { min-width:0; }\n.metric-pair span { display:block; font-size:12px; color:var(--muted); }\n.metric-pair strong { display:block; font-size:24px; font-weight:500; font-variant-numeric:tabular-nums; }\n.scale { display:flex; justify-content:space-between; color:var(--muted); font-size:12px; font-variant-numeric:tabular-nums; }\n@media(max-width:480px) { .metric-pair strong { font-size:21px; } }\n.presets { display:flex; }\n.allocation { position:relative; height:82px; margin-top:28px; }\n.capacity { position:absolute; left:0; top:12px; bottom:0; width:66.666667%; border:1px solid var(--rule); background:var(--surface); }\n.limit { position:absolute; left:66.666667%; top:0; bottom:0; border-left:2px dashed var(--ink); z-index:2; }\n.limit span { position:absolute; top:-22px; transform:translateX(-50%); font-size:12px; }\n#blocks { position:absolute; inset:24px 0 12px; }\n.block { position:absolute; top:0; height:100%; display:grid; place-items:center; background:var(--accent); color:var(--paper); border-right:2px solid var(--paper); transition:width .25s,left .25s; font-size:13px; }\n.block:nth-child(even) { background:var(--second); }\n.allocation[data-over='true'] .block:nth-child(n+3) { background:var(--ink); background-image:repeating-linear-gradient(135deg,transparent 0 5px,#ffffff30 5px 7px); }\n.lengths { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:8px; margin-top:18px; font-size:13px; font-variant-numeric:tabular-nums; }\n.lengths strong,.lengths span { display:block; }\n.lengths strong { font-size:15px; }.lengths span { color:var(--muted); }\n@media(max-width:480px) { .lengths { grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; } }\n","js":"const cases=[[2,2,3,3],[1,2,3,3],[1,1,2,2]], symbols=['A','B','C','D'];\nconst blocks=document.querySelector('#blocks'), lengths=document.querySelector('#lengths');\nfor(const s of symbols){const b=document.createElement('div');b.className='block';b.textContent=s;blocks.append(b);const row=document.createElement('div');row.innerHTML='<strong></strong><span></span><span></span>';lengths.append(row);}\nfunction draw(index){\n const lens=cases[index];let offset=0;\n lens.forEach((l,i)=>{const w=2**(-l),b=blocks.children[i],row=lengths.children[i];b.style.left=(offset/1.5*100)+'%';b.style.width=(w/1.5*100)+'%';row.children[0].textContent=symbols[i]+' · l = '+l;row.children[1].textContent='2⁻'+String(l).replace(/2/g,'²').replace(/3/g,'³').replace(/1/g,'¹')+' = '+viz.number(w,3);row.children[2].textContent=index===2?'—':(offset*2**l).toString(2).padStart(l,'0');offset+=w;});\n document.querySelector('#sum').textContent=viz.number(offset,2);document.querySelector('#comparison').textContent=offset<1?'<':offset===1?'=':'>';\n document.querySelector('.allocation').dataset.over=String(offset>1);\n document.querySelector('#explanation').textContent=viz.t(['slackExplain','fullExplain','overExplain'][index]);\n document.querySelectorAll('[data-case]').forEach(b=>b.setAttribute('aria-pressed',String(+b.dataset.case===index)));\n}\ndocument.querySelectorAll('[data-case]').forEach(b=>b.addEventListener('click',()=>draw(+b.dataset.case)));draw(1);","audio":false,"strings":{"chart":"Space occupied by four codewords. Capacity is 1; the axis extends to 1.5 to show overflow.","control":"Code-length assignment","eyebrow":"LENGTH → SPACE → EXISTENCE","full":"Exactly full","fullExplain":"Occupancy is exactly 1: A uses one half, B one quarter, and C and D one eighth each. Disjoint regions give codewords 0, 10, 110, and 111.","heading":"Why add 2⁻ˡ rather than the lengths themselves?","intro":"One more bit halves the occupied space. Compare three assignments and check whether they fit inside capacity 1.","note":"Each cell shows symbol and length, occupied fraction, and an example codeword. Blocks are ordered by length and aligned to a binary grid. Overflow illustrates an impossible allocation, not valid codewords.","over":"Over capacity","overExplain":"Occupancy is 1.5, beyond capacity. The one-bit words for A and B already consume all available space, leaving nowhere for C or D. No prefix code has these lengths.","slack":"Spare space","slackExplain":"Total occupancy is 0.75, leaving 0.25 free. Actual codewords appear below. Shortening A by one bit uses this spare space without lengthening any other codeword."}}
The diagram packs shorter codewords first. A length-l codeword can also represent a dyadic interval [k/2l,(k+1)/2l). Aligning these intervals to the binary grid without overlap constructs a prefix code. When occupancy is below 1, capacity remains unused. Code lengths are not unconditionally zero-sum: a codeword can be shortened without changing others if enough spare capacity remains; otherwise, space must be freed elsewhere.
Why does entropy bound average code length?
For a uniquely decodable binary symbol code, let L=∑xp(x)lx. The Kraft–McMillan inequality still gives K≤1. Normalize the code-space allocations into a distribution:
q(x)=K2−lx
Then −log2q(x)=lx+log2K. The cross-entropy and KL identity from the previous article separates the gap into two nonnegative terms:
L−H(p)=DKL(p∥q)−log2K≥0
The first term measures mismatch between p and the normalized allocation q. The second reflects unused code space: K≤1 implies −log2K≥0. This explains the average lower bound. The code must satisfy the decoding assumptions; an arbitrary one-to-one file mapping cannot be treated the same way while ignoring externally supplied lengths or boundaries.
For positive-probability symbols, choosing lx=⌈−log2p(x)⌉ yields a Shannon prefix code with:
H(X)≤L<H(X)+1
For blocks of n independent, identically distributed symbols, H(Xn)=nH(X) gives:
H(X)≤nLn<H(X)+n1
Every block still has an integer code length. Rounding overhead per original symbol becomes smaller. This expected-length result follows directly from block coding, without first invoking a typical set.
A fair die: why 2.667 questions for 2.585 bits?
A yes/no strategy forms a binary decision tree, with a root-to-leaf path for each prefix codeword. A fair die has entropy log26≈2.585 bits. An optimal tree has two leaves at depth 2 and four at depth 3:
L∗=62×2+4×3=38≈2.667.
The worst case still needs 3 questions. Entropy, average questions, and worst-case questions measure different things. Coding independent outcomes in blocks spreads the integer-length overhead over multiple symbols.
Huffman: read the codewords directly from the tree
Huffman coding repeatedly merges the two currently least probable nodes. Label each pair of branches 0 and 1; the path from root to leaf gives the codeword. For specified symbol probabilities, it minimizes expected length among binary prefix codes. Ties can produce different, equally optimal trees.
Read the branch bits along each path: A=0, B=10, C=110, D=111. Shallower leaves have shorter codewords.
Here p=(0.5,0.25,0.125,0.125), so:
L=0.5×1+0.25×2+0.125×3+0.125×3=1.75bits
Every positive probability has the form 2−l, so code length equals self-information and L=H=1.75 bits.
In general, Huffman guarantees average redundancy0≤L−H<1 bit per symbol. It does not guarantee that each individual length differs from its self-information by less than one bit. For two outcomes with probabilities (0.9,0.1), a symbol-by-symbol Huffman code still assigns one bit to each outcome, while entropy is approximately 0.469 bits.
Block Huffman coding narrows this gap, but its codebook grows rapidly with block length. Arithmetic coding represents the whole message differently.
Arithmetic coding: multiply probabilities, add information
Start with [0,1) and subdivide it according to the model probabilities. Keep the part corresponding to the next symbol, then subdivide that part again. If the current interval is [a,b) and the symbol occupies cumulative probability range [F,F+q), the next interval is:
[a+(b−a)F,a+(b−a)(F+q))
Its width is multiplied by the symbol’s model probability. With conditional probabilities, a message produces:
Wn=i=1∏nq(xi∣x<i)
−log2Wn=i=1∑n−log2q(xi∣x<i)
Below, the message is fixed as ABA. Only q(A)=p changes, with q(B)=1−p at every position. All three stages remain visible on the same [0,1) scale.
Preparing the visual
Turn a message into a narrowing interval
Keep ABA fixed and vary the model probability of A. Three stages share a 0–1 scale: widths multiply while negative logarithms add. A complete dyadic cell inside the final interval supplies an actual integer-length bitstring.
{"id":"source-arithmetic","title":"Turn a message into a narrowing interval","summary":"Keep ABA fixed and vary the model probability of A. Three stages share a 0–1 scale: widths multiply while negative logarithms add. A complete dyadic cell inside the final interval supplies an actual integer-length bitstring.","height":850,"html":"<p class=\"eyebrow\" data-i18n=\"eyebrow\"></p><h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p>\n<label class=\"control\" for=\"probability\"><span data-i18n=\"control\"></span><output id=\"probability-value\"></output></label><input id=\"probability\" type=\"range\" min=\"25\" max=\"75\" value=\"60\" step=\"1\">\n<p class=\"note\" data-i18n=\"axis\"></p><div class=\"intervals\" id=\"intervals\"></div>\n<div class=\"scale\"><span>0</span><span>1</span></div>\n<div class=\"formula\"><div id=\"product\"></div><div id=\"information\"></div></div>\n<div class=\"code-result\"><p data-i18n=\"binary\"></p><strong id=\"code\"></strong><p id=\"binary-range\"></p><div class=\"binary-track\"><div id=\"final-range\"></div><div id=\"binary-cell\"></div></div></div>\n<div class=\"metric-pair\"><div><span data-i18n=\"ideal\"></span><strong id=\"ideal\"></strong></div><div><span data-i18n=\"actual\"></span><strong id=\"actual\"></strong></div></div>\n<p class=\"note\" data-i18n=\"note\"></p>","css":".intro { margin:8px 0 18px; color:var(--muted); font-size:14px; }\n.control { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-top:18px; }\n.control output { min-width:4em; flex-shrink:0; text-align:center; background:var(--accent-soft); color:var(--accent); padding:2px 8px; border-radius:6px; font-weight:600; }\n.formula { margin-top:18px; padding:14px 0; border-block:1px solid var(--rule); font-size:16px; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }\n.copy-stack { display:grid; margin-top:14px; color:var(--muted); font-size:14px; }\n.copy-stack > * { grid-area:1/1; }\n.copy-stack .reserve { visibility:hidden; }\n.note { margin-top:14px; color:var(--muted); font-size:12px; }\n.metric-pair { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:18px; }\n.metric-pair > div { min-width:0; }\n.metric-pair span { display:block; font-size:12px; color:var(--muted); }\n.metric-pair strong { display:block; font-size:24px; font-weight:500; font-variant-numeric:tabular-nums; }\n.scale { display:flex; justify-content:space-between; color:var(--muted); font-size:12px; font-variant-numeric:tabular-nums; }\n@media(max-width:480px) { .metric-pair strong { font-size:21px; } }\n.intervals { display:grid; gap:14px; margin-top:16px; }\n.interval-label { display:flex; justify-content:space-between; align-items:baseline; gap:8px; font-size:13px; font-variant-numeric:tabular-nums; }\n.interval-label span { color:var(--muted); }\n.interval-track,.binary-track { position:relative; height:30px; background:var(--surface); margin-top:5px; }\n.parent-range,.selected-range { position:absolute; height:100%; }\n.parent-range { background:var(--accent-soft); box-shadow:inset 0 0 0 1px var(--rule); }\n.selected-range { background:var(--accent); transition:width .2s,left .2s; }\n.interval-row:nth-child(2) .selected-range { background:var(--second); }\n.formula { font-size:14px; }.formula div+div { margin-top:6px; }\n.code-result { margin-top:16px; font-size:13px; font-variant-numeric:tabular-nums; }\n#code { font-size:23px; letter-spacing:.08em; }#binary-range { color:var(--muted); }\n.binary-track { height:22px; }#final-range,#binary-cell { position:absolute; height:100%; }\n#final-range { background:var(--accent-soft); box-shadow:inset 0 0 0 1px var(--accent); }\n#binary-cell { background:var(--second); height:12px; top:5px; }\n@media(max-width:480px) { .interval-label { flex-wrap:wrap; }.interval-label span { font-size:12px; } }\n","js":"const input=document.querySelector('#probability'), rows=document.querySelector('#intervals'), message=['A','B','A'];\nfor(let i=0;i<3;i++){const row=document.createElement('div');row.className='interval-row';row.innerHTML='<div class=\"interval-label\"><strong></strong><span></span></div><div class=\"interval-track\"><div class=\"parent-range\"></div><div class=\"selected-range\"></div></div>';rows.append(row);}\nfunction place(el,lo,hi){el.style.left=(lo*100)+'%';el.style.width=((hi-lo)*100)+'%';}\nfunction draw(){const p=+input.value/100;document.querySelector('#probability-value').textContent=viz.number(p,2);let lo=0,hi=1;\n message.forEach((symbol,i)=>{const beforeLo=lo,beforeHi=hi,w=hi-lo,cut=lo+w*p;if(symbol==='A')hi=cut;else lo=cut;const row=rows.children[i];row.querySelector('strong').textContent=message.slice(0,i+1).join('')+' · × '+viz.number(symbol==='A'?p:1-p,2);row.querySelector('.interval-label span').textContent='['+viz.number(lo,4)+', '+viz.number(hi,4)+')';place(row.querySelector('.parent-range'),beforeLo,beforeHi);place(row.querySelector('.selected-range'),lo,hi);});\n const width=hi-lo,info=-Math.log2(width);let m=0,k=0;for(;m<24;m++){k=Math.ceil(lo*2**m-1e-10);if((k+1)/2**m<=hi+1e-12)break;}\n const a=k/2**m,b=(k+1)/2**m;\n document.querySelector('#product').textContent='W = '+viz.number(p,2)+' × '+viz.number(1-p,2)+' × '+viz.number(p,2)+' = '+viz.number(width,5);\n document.querySelector('#information').textContent='−log₂ W = '+viz.number(-Math.log2(p),2)+' + '+viz.number(-Math.log2(1-p),2)+' + '+viz.number(-Math.log2(p),2)+' ≈ '+viz.number(info,2)+' bit';\n document.querySelector('#code').textContent=k.toString(2).padStart(m,'0');document.querySelector('#binary-range').textContent='['+viz.number(a,5)+', '+viz.number(b,5)+') ⊆ ABA';\n place(document.querySelector('#final-range'),lo,hi);place(document.querySelector('#binary-cell'),a,b);\n document.querySelector('#ideal').textContent=viz.number(info,2)+' bit';document.querySelector('#actual').textContent=m+' bit';\n}\ninput.addEventListener('input',draw);draw();","audio":false,"strings":{"actual":"Bits emitted for this message","axis":"All rows share [0, 1). Right-hand labels give retained interval endpoints.","binary":"Choose a complete cell on the binary grid","control":"Model probability q(A) = p","eyebrow":"PROBABILITY PRODUCTS → INFORMATION SUMS","heading":"Why does a narrower interval require more bits?","ideal":"Ideal information −log₂ W","intro":"The message stays ABA. Pale regions show the interval before subdivision; solid regions are retained. All three stages remain visible together.","note":"At the bottom, pale blue is ABA and the gold cell lies entirely inside it. Send only the gold cell’s binary prefix. Both ends share the model and message length 3. The control spans 0.25–0.75 and uses ideal interval arithmetic; displayed decimals are rounded. Actual bit length remains integer."}}
At p=0.6, the intervals are [0,0.6), [0.36,0.6), and [0.36,0.504). Final width is 0.6×0.4×0.6=0.144, giving about 2.796 bits of ideal information.
To emit actual bits, one clear termination method selects a complete dyadic cell [k/2m,(k+1)/2m) inside the final interval and sends its m-bit prefix. For example, 011 represents [0.375,0.5), entirely inside the ABA interval. A decoder using the same subdivisions can identify the message. This example also assumes a known length of 3; a real format needs a shared length or termination rule.
Arithmetic coding still emits an integer number of bits. It accumulates information across symbols and pays a finite termination overhead for the whole message. With ideal precision and known block length, this construction can achieve −log2q(xn)≤l(xn)<−log2q(xn)+2. Finite-precision implementations also account for renormalization, quantized probabilities, and headers. See the Stanford arithmetic coding notes.
Entropy rate: what remains uncertain after using context?
Independent symbols have joint entropy nH(X). With dependence, start from the chain rule:
H(X1,…,Xn)=i=1∑nH(Xi∣X1,…,Xi−1)
When the limit exists, the entropy rate is:
Hˉ=n→∞limn1H(X1,…,Xn)
For a stationary source on a finite alphabet, this limit exists and equals the limiting conditional entropy with increasingly long histories. The sample-path AEP below generally also requires ergodicity.
For a concrete example, start with a fair bit X1. At each later position, independently flip the previous bit with probability r, or retain it with probability 1−r. Every marginal remains fair, with entropy 1 bit. Given the previous bit, uncertainty is only h2(r):
H(Xn)=1+(n−1)h2(r),Hˉ=h2(r)
At r=0.1, the rate is approximately 0.469 bits per symbol. Compression can exploit this contextual redundancy even though single-symbol marginal frequencies remain uniform.
Give the same sequence to two predictors
Both fixed samples have the same total zero/one frequencies. The independent model always assigns probability 1/2 to the next bit. With the previous bit known, the context model assigns 1−r to staying and r to flipping. Change r and reveal bits to compare cumulative ideal lengths.
Preparing the visual
Half zeros, half ones. Why different code lengths?
Reveal two balanced fixed samples bit by bit. Compare cumulative ideal lengths from a fair independent model and a Markov model with flip probability r, whose entropy rate is h₂(r).
{"id":"source-context","title":"Half zeros, half ones. Why different code lengths?","summary":"Reveal two balanced fixed samples bit by bit. Compare cumulative ideal lengths from a fair independent model and a Markov model with flip probability r, whose entropy rate is h₂(r).","height":750,"html":"<p class=\"eyebrow\" data-i18n=\"eyebrow\"></p><h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p>\n<div class=\"presets\" role=\"group\" data-i18n-label=\"samples\"><button data-sample=\"runs\" data-i18n=\"runs\"></button><button data-sample=\"mixed\" data-i18n=\"mixed\"></button></div>\n<label class=\"control\" for=\"flip\"><span data-i18n=\"flip\"></span><output id=\"flip-value\"></output></label><input id=\"flip\" type=\"range\" min=\"5\" max=\"95\" step=\"5\" value=\"10\">\n<div class=\"source-metrics\"><span>H(Xᵢ) = 1 bit</span><span>H̄ = h₂(r) = <output id=\"entropy-rate\"></output> bit</span></div>\n<div id=\"tokens\" role=\"img\" data-i18n-label=\"tokens\"></div>\n<div class=\"toolbar\"><button data-prev data-i18n=\"prev\"></button><button data-next data-i18n=\"next\"></button><button data-play data-i18n=\"play\" aria-pressed=\"false\"></button><span data-step></span></div>\n<div class=\"metrics\"><div class=\"metric\"><span data-i18n=\"iid\"></span><strong id=\"iid-loss\"></strong></div><div class=\"metric\"><span data-i18n=\"markov\"></span><strong id=\"markov-loss\"></strong></div></div>\n<div class=\"current\"><span data-i18n=\"current\"></span><strong id=\"current-loss\"></strong></div>\n<div class=\"cumulative\" role=\"img\" data-i18n-label=\"curve\"><div class=\"axis\"><span data-i18n=\"axis\"></span><span id=\"length-scale\"></span></div><svg viewBox=\"0 0 600 160\" preserveAspectRatio=\"none\"><path class=\"grid\" d=\"M0 80H600 M0 160H600\"/><path id=\"iid-curve\" class=\"iid\"/><path id=\"context-curve\" class=\"context\"/><circle id=\"context-dot\" r=\"4\"/></svg><div class=\"axis\"><span>0 bit</span><span data-i18n=\"positions\"></span><span>16</span></div></div>\n<div class=\"legend\"><span class=\"iid\" data-i18n=\"iid\"></span><span class=\"context\" data-i18n=\"markov\"></span></div>\n<details class=\"audit-details\"><summary data-i18n=\"details\"></summary><div class=\"formula\" id=\"sample-formula\"></div><div class=\"formula\" id=\"expected\"></div><p class=\"note\" data-i18n=\"note\"></p></details>","css":"\n.intro { margin:8px 0 14px; color:var(--muted); font-size:14px; }\n.presets { display:flex; flex-wrap:wrap; margin:12px 0; }\n.presets button { flex:1 1 auto; min-width:0; }\n.control { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-top:12px; font-size:14px; }\n.control output { flex-shrink:0; font-variant-numeric:tabular-nums; font-weight:600; }\n.metrics { grid-template-columns:repeat(2,minmax(0,1fr)); margin:12px 0; }\n.metric strong { font-size:23px; }.metric span { font-size:12px; overflow-wrap:anywhere; }\n.note { color:var(--muted); font-size:12px; line-height:1.65; margin-top:10px; }\n.formula { font-size:14px; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; margin:10px 0; }\n.copy-stack { display:grid; margin:12px 0; font-size:13px; line-height:1.65; }\n.copy-stack > p { grid-area:1/1; min-width:0; }.reserve { visibility:hidden; pointer-events:none; user-select:none; }\n.audit-details { border-top:1px solid var(--rule); margin-top:14px; padding-top:10px; font-size:13px; }\n.audit-details summary { cursor:pointer; color:var(--accent); min-height:32px; padding:5px 0; }\n.audit-details summary:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }\n@media(max-width:480px){.intro{font-size:13px}.metric strong{font-size:21px}.presets button{font-size:13px}.formula{font-size:13px}}\n\n.source-metrics { display:flex; flex-wrap:wrap; gap:4px 20px; font-size:13px; margin:8px 0 12px; font-variant-numeric:tabular-nums; }\n#tokens { display:grid; grid-template-columns:repeat(16,minmax(0,1fr)); gap:4px; }\n.token { display:grid; place-items:center; height:32px; background:var(--surface); border-bottom:2px solid var(--rule); border-radius:3px; color:var(--muted); font-variant-numeric:tabular-nums; }\n.token.revealed { color:var(--ink); border-color:var(--accent); background:var(--accent-soft); }.token.flip { border-color:var(--second); }.token.current { outline:2px solid var(--ink); outline-offset:-2px; }\n.current { display:flex; flex-wrap:wrap; justify-content:space-between; gap:4px 12px; font-size:13px; padding-bottom:8px; }.current strong { font-variant-numeric:tabular-nums; font-weight:500; }\n.cumulative { margin-top:8px; }.cumulative svg { height:135px; width:100%; overflow:visible; }.grid { fill:none; stroke:var(--rule); stroke-width:1; vector-effect:non-scaling-stroke; }\n.cumulative path.iid { stroke:var(--muted); stroke-dasharray:5 4; }.cumulative path.context { stroke:var(--accent); }.cumulative path:not(.grid) { fill:none; stroke-width:2; vector-effect:non-scaling-stroke; }.cumulative circle { fill:var(--accent); }\n.axis { display:flex; justify-content:space-between; color:var(--muted); font-size:11px; }.legend { display:flex; flex-wrap:wrap; gap:4px 16px; font-size:12px; margin-top:5px; }.legend span::before{content:'';display:inline-block;width:18px;border-top:2px solid var(--accent);margin-right:5px;vertical-align:middle}.legend .iid::before{border-color:var(--muted);border-top-style:dashed}\n@media(max-width:480px){#tokens{grid-template-columns:repeat(8,minmax(0,1fr))}.token{height:26px}.cumulative svg{height:110px}.toolbar:has([data-play]){margin-top:12px;padding-top:10px}.metrics{margin:10px 0}}\n","js":"const $=s=>document.querySelector(s),samples={runs:'0000000011111111',mixed:'0100110101100011'};let sample='runs',step=0;\nfor(let i=0;i<16;i++){const e=document.createElement('span');e.className='token';$('#tokens').append(e);}\nfunction draw(){const seq=samples[sample],r=+$('#flip').value/100,n=step+1,h=viz.entropy([r,1-r]);let sum=0,k=0,pts=['0,160'];\n const fullLength=s=>1+[...s].slice(1).reduce((a,b,i)=>a-Math.log2(b===s[i]?1-r:r),0);const scale=Math.max(24,Math.ceil(Math.max(...Object.values(samples).map(fullLength))/8)*8);$('#length-scale').textContent=scale;\n const losses=[...seq].map((b,i)=>-Math.log2(i===0?.5:b===seq[i-1]?1-r:r));\n losses.slice(0,n).forEach((l,i)=>{sum+=l;pts.push(((i+1)/16*600)+','+(160-sum/scale*160));if(i&&seq[i]!==seq[i-1])k++;});\n $('#flip-value').textContent=viz.number(r,2);$('#entropy-rate').textContent=viz.number(h,3);$('#iid-loss').textContent=n+' bit';$('#markov-loss').textContent=viz.number(sum,3)+' bit';\n const probability=2**(-losses[n-1]);$('#current-loss').textContent='q = '+viz.number(probability,2)+' → '+viz.number(losses[n-1],3)+' bit';\n [...$('#tokens').children].forEach((e,i)=>{e.textContent=i<n?seq[i]:'·';e.classList.toggle('revealed',i<n);e.classList.toggle('flip',i>0&&i<n&&seq[i]!==seq[i-1]);e.classList.toggle('current',i===step);});\n $('#tokens').setAttribute('aria-label',viz.t('tokens')+' '+seq.slice(0,n)+'; n='+n);$('#iid-curve').setAttribute('d','M0,160 L'+(n/16*600)+','+(160-n/scale*160));$('#context-curve').setAttribute('d','M'+pts.join(' L'));$('#context-dot').setAttribute('cx',n/16*600);$('#context-dot').setAttribute('cy',160-sum/scale*160);\n $('#sample-formula').textContent='L = 1 − '+k+' log₂ r − '+(n-1-k)+' log₂(1−r) = '+viz.number(sum,3)+' bit';$('#expected').textContent='H(X¹⁶) = 1 + 15 h₂(r) = '+viz.number(1+15*h,3)+' bit';\n $('.cumulative').setAttribute('aria-label',viz.t('curve')+' n='+n+', '+viz.t('iid')+': '+n+' bit; '+viz.t('markov')+': '+viz.number(sum,3)+' bit.');document.querySelectorAll('[data-sample]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.sample===sample)));}\nconst sequence=viz.sequence({count:16,render(s){step=s;draw();}});$('#flip').addEventListener('input',()=>{sequence.pause();draw();});document.querySelectorAll('[data-sample]').forEach(e=>e.addEventListener('click',()=>{sample=e.dataset.sample;sequence.goTo(0);}));","audio":false,"strings":{"axis":"Cumulative length · bit","current":"Current context prediction","curve":"Cumulative ideal sample length under both models","details":"Sample length versus average entropy rate","eyebrow":"One message, two probability models","flip":"Context model flip probability r","heading":"Half zeros, half ones. Why different code lengths?","iid":"Independent: q=½","intro":"Each fixed sample has eight zeros and eight ones. Reveal bits to compare predictions with and without the previous bit.","markov":"Context model","mixed":"Mixed order","next":"Next bit","note":"These are fixed samples, not simulated sources. Both source models start with a fair bit. The context model then makes independent flip decisions, leaving every marginal fair; r=0.5 gives the independent source. An orange lower edge marks a flip. The labeled vertical limit adjusts with r; both samples share the same scale at a given r. L is this sample’s ideal length; H(X¹⁶) averages over all samples under the model. A single L/16 is not the entropy rate.","pause":"Pause","play":"Play bits","positions":"Bits revealed","prev":"Previous bit","runs":"Long runs","samples":"Fixed sample","tokens":"Revealed bits; the current bit is outlined"}}
With k flips among the first n bits, the context model assigns
L(xn)=1−klog2r−(n−1−k)log2(1−r).
The first bit costs 1 bit. Every later stay or flip costs its conditional self-information. At r=0.5, every step costs 1 bit. At r=0.1, stays are cheap and unexpected flips expensive. Context does not shorten every message: a sample with frequent flips can cost more under a model that considers flips rare. Averaging over that source model, rather than one fixed sample, gives 1+(n−1)h2(r).
AEP: how can a small set carry most of the probability?
For an IID source, average sequence information is an average of IID random variables. The law of large numbers yields the asymptotic equipartition property (AEP):
−n1log2P(Xn)=n1i=1∑n−log2P(Xi)PH(X)
For fixed tolerance ε>0, the typical set Tn,ε consists of sequences whose average information is within H±ε. Its total probability tends to 1, while each typical sequence satisfies:
2−n(H+ε)≤P(xn)≤2−n(H−ε)
Distinguish two fractions: the fraction of all possible sequences, and the probability of sampling one under the source distribution. The following example fixes P(1)=0.2 and ε=0.12, using exact binomial probabilities rather than random simulation.
Preparing the visual
Few sequences can carry most of the probability
Fix P(1)=0.2 and tolerance 0.12 bits, then vary sequence length. The histogram shows average-information probabilities; blue marks typical sequences. Below, compare source probability with the fraction of all binary sequences.
{"id":"source-aep","title":"Few sequences can carry most of the probability","summary":"Fix P(1)=0.2 and tolerance 0.12 bits, then vary sequence length. The histogram shows average-information probabilities; blue marks typical sequences. Below, compare source probability with the fraction of all binary sequences.","height":850,"html":"<p class=\"eyebrow\" data-i18n=\"eyebrow\"></p><h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p>\n<div class=\"presets\" role=\"group\" data-i18n-label=\"control\"><button data-n=\"4\">n = 4</button><button data-n=\"16\">n = 16</button><button data-n=\"64\">n = 64</button><button data-n=\"256\">n = 256</button></div>\n<p class=\"note\" data-i18n=\"vertical\"></p>\n<div class=\"distribution\" role=\"img\" data-i18n-label=\"chart\"><div class=\"typical-band\"></div><div class=\"entropy-marker\"></div><div id=\"bars\"></div><span class=\"ceiling\">0.6</span></div>\n<div class=\"scale\"><span>0</span><span>H ≈ 0.722</span><span>2.4 bit</span></div><p class=\"note\" data-i18n=\"horizontal\"></p>\n<div class=\"formula\">| −log₂ P(Xⁿ) / n − H | ≤ 0.12</div>\n<div class=\"mass\"><div class=\"mass-label\"><span data-i18n=\"mass\"></span><strong id=\"mass\"></strong></div><div class=\"mass-track\"><div id=\"mass-fill\"></div></div></div>\n<div class=\"mass\"><div class=\"mass-label\"><span data-i18n=\"count\"></span><strong id=\"fraction\"></strong></div><div class=\"mass-track\"><div id=\"count-fill\"></div></div></div>\n<div class=\"count-formula\" id=\"count-formula\"></div>\n<p class=\"note\" data-i18n=\"note\"></p>","css":".intro { margin:8px 0 18px; color:var(--muted); font-size:14px; }\n.control { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-top:18px; }\n.control output { min-width:4em; flex-shrink:0; text-align:center; background:var(--accent-soft); color:var(--accent); padding:2px 8px; border-radius:6px; font-weight:600; }\n.formula { margin-top:18px; padding:14px 0; border-block:1px solid var(--rule); font-size:16px; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }\n.copy-stack { display:grid; margin-top:14px; color:var(--muted); font-size:14px; }\n.copy-stack > * { grid-area:1/1; }\n.copy-stack .reserve { visibility:hidden; }\n.note { margin-top:14px; color:var(--muted); font-size:12px; }\n.metric-pair { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:18px; }\n.metric-pair > div { min-width:0; }\n.metric-pair span { display:block; font-size:12px; color:var(--muted); }\n.metric-pair strong { display:block; font-size:24px; font-weight:500; font-variant-numeric:tabular-nums; }\n.scale { display:flex; justify-content:space-between; color:var(--muted); font-size:12px; font-variant-numeric:tabular-nums; }\n@media(max-width:480px) { .metric-pair strong { font-size:21px; } }\n.presets { display:flex; }.presets button { font-size:13px; padding-inline:6px; }\n.distribution { position:relative; height:210px; margin-top:12px; border-bottom:1px solid var(--muted); background:repeating-linear-gradient(to top,transparent 0 calc(33.333% - 1px),var(--rule) calc(33.333% - 1px) 33.333%); }\n.typical-band { position:absolute; top:0; bottom:0; left:25.080337%; width:10%; background:var(--accent-soft); }\n.entropy-marker { position:absolute; top:0; bottom:0; left:30.080337%; border-left:1px dashed var(--accent); }\n#bars { position:absolute; inset:0; }.bin { position:absolute; bottom:0; width:2.5%; padding-right:1px; }.bin-normal { background:var(--muted); }.bin-typical { background:var(--accent); }.bin > div { width:100%; }\n.ceiling { position:absolute; top:0; right:0; font-size:11px; color:var(--muted); }\n.mass { margin-top:16px; }.mass-label { display:flex; justify-content:space-between; gap:12px; align-items:baseline; font-size:13px; }.mass-label strong { flex-shrink:0; font-variant-numeric:tabular-nums; }.mass-track { height:9px; background:var(--surface); margin-top:6px; }.mass-track > div { height:100%; background:var(--accent); }#count-fill { background:var(--second); }\n.count-formula { margin-top:12px; font-size:13px; font-variant-numeric:tabular-nums; }\n@media(max-width:480px) { .presets { display:grid; grid-template-columns:repeat(2,1fr); }.distribution { height:180px; } }\n\n.mass-label strong { width:10em; text-align:right; }.count-formula { min-height:3.2em; }\n.distribution + .scale { position:relative; }\n.distribution + .scale span:nth-child(2) { position:absolute; left:30.080337%; transform:translateX(-50%); }\n.bin, .bin > div { transition:height .36s cubic-bezier(.22,1,.36,1); }\n.mass-track > div { transition:width .36s cubic-bezier(.22,1,.36,1); }\n","js":"const p=.2,H=viz.entropy([p,1-p]),epsilon=.12,binWidth=.06,chart=document.querySelector('#bars');\nfor(let i=0;i<40;i++){const b=document.createElement('div');b.className='bin';b.style.left=(i*2.5)+'%';b.innerHTML='<div class=\"bin-normal\"></div><div class=\"bin-typical\"></div>';chart.append(b);}\nfunction draw(n){const bins=Array.from({length:40},()=>({normal:0,typical:0}));let mass=0,count=0,choose=1,prob=(1-p)**n;\n for(let k=0;k<=n;k++){const info=-(k*Math.log2(p)+(n-k)*Math.log2(1-p))/n,typical=Math.abs(info-H)<=epsilon+1e-12,index=Math.min(39,Math.floor(info/binWidth));bins[index][typical?'typical':'normal']+=prob;if(typical){mass+=prob;count+=choose;}if(k<n){prob*=((n-k)/(k+1))*(p/(1-p));choose*=(n-k)/(k+1);}}\n const fraction=count/2**n;bins.forEach((b,i)=>{const el=chart.children[i],sum=b.normal+b.typical;el.style.height=(sum/.6*100)+'%';el.children[0].style.height=(sum?b.normal/sum*100:0)+'%';el.children[1].style.height=(sum?b.typical/sum*100:0)+'%';});\n document.querySelector('#mass').textContent=viz.number(mass*100,2)+'%';document.querySelector('#fraction').textContent=fraction>=.0001?viz.number(fraction*100,2)+'%':viz.number(fraction*100/10**Math.floor(Math.log10(fraction*100)),2)+' × 10^'+Math.floor(Math.log10(fraction*100))+'%';\n document.querySelector('#mass-fill').style.width=mass*100+'%';document.querySelector('#count-fill').style.width=fraction*100+'%';\n document.querySelector('#count-formula').textContent='|T| ≈ 2^'+viz.number(Math.log2(count),2)+' · '+viz.t('total')+' = 2^'+n;\n document.querySelectorAll('[data-n]').forEach(b=>b.setAttribute('aria-pressed',String(+b.dataset.n===n)));\n}\ndocument.querySelectorAll('[data-n]').forEach(b=>b.addEventListener('click',()=>draw(+b.dataset.n)));draw(16);","audio":false,"strings":{"chart":"Distribution of average information across block lengths, with a fixed typical band of 0.12 bits on either side of entropy.","control":"Sequence length","count":"Typical count / all sequences","eyebrow":"TYPICAL SETS: COUNT VERSUS PROBABILITY","heading":"How can about 2ⁿᴴ sequences hold most of the probability?","horizontal":"Horizontal: average information −log₂ P(Xⁿ) / n. Pale blue spans H ± 0.12; the dashed line is H. Blue bars are typical mass, gray bars the rest.","intro":"All 2ⁿ binary sequences are possible, but they are not equally likely. Change only n and watch average information concentrate near H.","mass":"Source probability of the typical set","note":"Exact binomial sums, with rounded display. Counting adds combinations; probability also weights each sequence. These four lengths illustrate concentration, not guaranteed monotonic growth at every finite length. With fixed tolerance, 2ⁿᴴ is an exponential-scale approximation.","total":"All sequences","vertical":"Vertical: probability per 0.06-bit bin, fixed range 0–0.6."}}
A particular sequence with k ones has probability 0.2k0.8n−k. There are (kn) such sequences. Their combined probability is therefore (kn)0.2k0.8n−k, whereas counting them adds only (kn). This explains why the two fractions differ so much.
If typical-set probability is at least 1−δ, the bounds on individual probabilities imply:
(1−δ)2n(H−ε)≤∣Tn,ε∣≤2n(H+ε)
“About 2nH sequences” describes an exponential-rate approximation, not an exact count at finite n. With a fixed tolerance, coverage need not increase monotonically at every successive block length. For a uniform source, all sequences can be typical; a tiny fraction of all sequences is a feature of this nonuniform example, not a universal AEP requirement.
Indexing typical sequences explains asymptotic fixed-rate coding with small error probability. Strictly lossless compression must also recover atypical sequences, for example with an escape flag and a fallback code; they cannot simply be discarded. See the Stanford AEP notes.
A language model supplies probabilities; an entropy coder emits bits
A language model provides q(xi∣x<i). An entropy coder, such as arithmetic coding, turns those probabilities into a reversible bitstream. Ideal rate on a particular sample is:
n1i∑−log2q(xi∣x<i)
This is empirical negative log-likelihood; taking expectation under the true source gives the corresponding cross-entropy. Loss computed with natural logarithms must be divided by ln2 to obtain bits. With consistent units and data representation, lower prediction loss usually means lower ideal coding cost. The average entropy bound does not require every individual message to exceed the source’s average entropy.
A real compressor must also account for the model, vocabulary, length or end marker, headers, and numerical precision. Both ends must reproduce identical probabilities. The ideal relationship becomes more representative when model cost can be amortized over enough data. Language Modeling Is Compression studies this connection and compression with language models.
BPE shortens token sequences by merging common adjacent symbols, while also changing vocabulary, probabilities, and modeling difficulty. Across tokenizers, compare a common unit such as bits per byte. Fewer tokens or lower per-token loss alone does not establish better text compression. See Tokens and Sampling.
Method
How length is allocated
Main constraint
Symbol-by-symbol Huffman
An integer codeword for each symbol
Average redundancy below 1 bit per symbol; blocks can reduce it further
Arithmetic / range coding
Accumulate message probability through interval subdivision
Final bit length remains integer; model, precision, and termination must agree
ANS
Entropy coding through an integer state
Also depends on a probability model and finite precision; organizes state and output differently