🧩 Python Information Lab — Entropy 🐍
Posted on: December 3, 2026
Description:
Two messages contain the same 4,096 bytes. Each possible byte value appears exactly sixteen times in each message. One compresses to 315 bytes. The other takes 4,107. To explain that difference, start with what you know before you look at a byte.
Guess a byte from its frequency
Pick a position uniformly at random. In a message made entirely of the letter A, you already know the byte at that position. In a message containing equal numbers of A and B, you need one bit to distinguish the two possibilities if all you know is the frequency of each.
For a byte with observed frequency p, its surprise is log₂(1/p) bits. Weight each surprise by how often that byte occurs and add the contributions. The result is empirical zero-order Shannon entropy, H₀, measured in bits per byte. “Zero-order” means the calculation ignores the preceding bytes.
def byte_entropy(data):
if not data:
return 0.0
n = len(data)
return fsum((count / n) * log2(n / count)
for count in Counter(data).values())
For alternating A and B, H₀ is exactly 1. Once you know the alternation rule and the previous letter, you can predict the next letter exactly. That extra information lives in the ordering.
Change the order while keeping the counts
Build a message by repeating the byte values 0 through 255 sixteen times. Shuffle a copy with a fixed seed. Both histograms are flat, so both give log₂(256) = 8 bits per byte. Compress each input with the same settings and verify that decompression restores every byte.
cycle = bytes(range(256)) * 16
shuffled = bytearray(cycle)
Random(42).shuffle(shuffled)
assert Counter(cycle) == Counter(shuffled)
packed = zlib.compress(shuffled, level=9)
assert zlib.decompress(packed) == bytes(shuffled)
| 4,096-byte input | H₀ (bits per byte) | Compressed size |
|---|---|---|
| Only A | 0 | 28 bytes |
| Alternating A and B | 1 | 28 bytes |
| Repeating 0–255 cycle | 8 | 315 bytes |
| Shuffled copy of the cycle | 8 | 4,107 bytes |
These are measured stream sizes from Python 3.13.5 with zlib 1.2.12 at level 9. The two 28-byte results are a coincidence of this input length and compressor. Even the all-A stream needs enough information to reconstruct its content.
Look 256 bytes back
In the ordered cycle, all 3,840 positions after the first block match the byte 256 places earlier. In this shuffle, only 13 of 3,840 do. That fixed-lag test makes the chosen pattern visible. DEFLATE searches for useful repeated sequences at multiple distances and can encode a match using its length and backward distance.
The shuffled stream ends up eleven bytes larger than its input because the compressor still has to emit a valid stream, including framing. Zero-order entropy describes the observed frequencies. To learn how many bytes a particular compressor saves, run it on the actual sequence.
No comments yet. Be the first to comment!