{"id":137,"date":"2026-11-13T12:32:25","date_gmt":"2026-11-13T04:32:25","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-arithmetic-coding-narrows-a-fraction\/"},"modified":"2026-11-13T21:51:06","modified_gmt":"2026-11-13T13:51:06","slug":"how-arithmetic-coding-narrows-a-fraction","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-arithmetic-coding-narrows-a-fraction\/","title":{"rendered":"How arithmetic coding narrows a fraction"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Arithmetic coding<\/strong> encodes a message as a single fraction of the unit interval. Each symbol narrows the current interval to the subinterval proportional to the symbol&#8217;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 <strong>\u2212log\u2082 of the probability of the message<\/strong>, which can be a fractional number of bits per symbol. Huffman coding cannot, because it assigns each symbol a whole number of bits.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 \u2212log\u2082 p bits by shrinking an interval, so the cost can be shared across symbols.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Start with the interval [0, 1), represented as integers [low, high).<\/li>\n<li>For each symbol, partition the current interval in proportion to the cumulative model probabilities and replace the interval by the symbol&#8217;s piece.<\/li>\n<li>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.<\/li>\n<li>Handle the straddling case, where the interval lies in the middle half, by tracking pending underflow bits and rescaling around the midpoint.<\/li>\n<li>The decoder maintains the same interval and a code value, finds which symbol&#8217;s subinterval contains the code, and applies the same rescaling.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the model updates on only one side<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Adapt the encoder&#8217;s counts and leave the decoder&#8217;s model static<\/td>\n<td>The intervals diverge. The decoder reads a different symbol and every later symbol is wrong.<\/td>\n<\/tr>\n<tr>\n<td>Emit a Huffman code and call it arithmetic coding<\/td>\n<td>Huffman assigns an integer length to one symbol. Arithmetic coding narrows a shared interval and can spend a fraction of a bit.<\/td>\n<\/tr>\n<tr>\n<td>Ignore the middle-half rescale<\/td>\n<td>The integer range collapses toward zero width while the leading bit is still ambiguous. The coder then has no precision left.<\/td>\n<\/tr>\n<tr>\n<td>Claim a compression ratio without stating the model<\/td>\n<td>The coder approaches the entropy of the model it was given. The model is the rest of the compressor.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>abc<\/code> and decoding those bits returns <code>abc<\/code>.<\/p>\n\n<pre><code class=\"language-python\">FULL, HALF, QUARTER = 1 &lt;&lt; 16, 1 &lt;&lt; 15, 1 &lt;&lt; 14\nsymbols = (&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)\ncounts = {ch: 1 for ch in symbols}\ntotal = 3\n\ndef cumulative(ch):\n    start = 0\n    for item in symbols:\n        if item == ch:\n            return start, counts[item]\n        start += counts[item]\n\ndef encode(text):\n    low, high, pending = 0, FULL, 0\n    bits = []\n\n    def emit(bit):\n        nonlocal pending\n        bits.append(bit)\n        while pending:\n            bits.append(1 - bit)\n            pending -= 1\n\n    for ch in text:\n        span = high - low\n        start, width = cumulative(ch)\n        high = low + span * (start + width) \/\/ total\n        low = low + span * start \/\/ total\n        while True:\n            if high &lt;= HALF:\n                emit(0)\n            elif low &gt;= HALF:\n                emit(1)\n                low -= HALF\n                high -= HALF\n            elif low &gt;= QUARTER and high &lt;= 3 * QUARTER:\n                pending += 1\n                low -= QUARTER\n                high -= QUARTER\n            else:\n                break\n            low *= 2\n            high *= 2\n    pending += 1\n    emit(0 if low &lt; QUARTER else 1)\n    return bits\n\ndef decode(bits, length):\n    low, high = 0, FULL\n    code = 0\n    index = 0\n\n    def read():\n        nonlocal index\n        if index &gt;= len(bits):\n            return 0\n        bit = bits[index]\n        index += 1\n        return bit\n\n    for _ in range(16):\n        code = code * 2 + read()\n    out = []\n    for _ in range(length):\n        span = high - low\n        value = ((code - low + 1) * total - 1) \/\/ span\n        start = 0\n        for ch in symbols:\n            if start &lt;= value &lt; start + counts[ch]:\n                width = counts[ch]\n                chosen = ch\n                break\n            start += counts[ch]\n        out.append(chosen)\n        high = low + span * (start + width) \/\/ total\n        low = low + span * start \/\/ total\n        while True:\n            if high &lt;= HALF:\n                pass\n            elif low &gt;= HALF:\n                low -= HALF\n                high -= HALF\n                code -= HALF\n            elif low &gt;= QUARTER and high &lt;= 3 * QUARTER:\n                low -= QUARTER\n                high -= QUARTER\n                code -= QUARTER\n            else:\n                break\n            low *= 2\n            high *= 2\n            code = code * 2 + read()\n    return &quot;&quot;.join(out)\n\nbits = encode(&quot;abc&quot;)\nassert decode(bits, 3) == &quot;abc&quot;\nprint(decode(bits, 3))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>CABAC<\/strong> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for arithmetic coding returns the shrinking interval and the model agreement the decoder requires. <strong>Arithmetic coding represents a message by a shrinking probability interval, so the encoded length can approach the ideal fractional bit cost of the model.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;s probability. The encoder emits bits as soon as they are determined by the shrinking interval, and it uses renormalization to keep&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,41],"tags":[],"class_list":["post-137","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-compression"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=137"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/137\/revisions"}],"predecessor-version":[{"id":536,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/137\/revisions\/536"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}