{"id":194,"date":"2026-11-13T12:34:11","date_gmt":"2026-11-13T04:34:11","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-hyperloglog-estimates-a-cardinality\/"},"modified":"2026-11-13T21:52:22","modified_gmt":"2026-11-13T13:52:22","slug":"how-hyperloglog-estimates-a-cardinality","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-hyperloglog-estimates-a-cardinality\/","title":{"rendered":"How HyperLogLog estimates a cardinality"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>HyperLogLog<\/strong> estimates the number of distinct items in a stream from the position of the first 1-bit in each item&#8217;s hash. Items are bucketed by the first p bits of the hash, into m = 2^p registers. Each register stores the maximum number of leading zeros, plus one, seen in that bucket. The estimate is a harmonic mean of 2 raised to those registers, multiplied by a bias constant near <strong>0.7213 \/ (1 + 1.111\/m)<\/strong>, times m\u00b2. The relative error is about <strong>1.04 \/ sqrt(m)<\/strong>. The sketch does not store the items.<\/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\">An exact cardinality stores every distinct key. A stream that is larger than memory cannot. Leading zeros of a uniform hash are a geometric random variable: the chance the first 1 appears at bit k is 2^{\u2212k}. The maximum of many such variables encodes how many hashes were observed, and the harmonic mean across buckets reduces the variance of that very noisy maximum.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The raw estimate is biased for small cardinalities and saturates in a known way for huge ones. Practical implementations switch to a linear counting regime when many registers are still zero, and they correct the large-cardinality end. The paper&#8217;s raw formula is the middle regime.<\/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 m registers the standard error is about 1.04\/sqrt(m), so m = 2^14 gives roughly one percent. Memory is m bytes if each register holds a small integer, which it does, because a leading-zero count fits in a few bits. The estimate is not an integer count of a stored set. Merging two sketches is a register-wise maximum, which is associative, so partial streams combine.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The hashes must be uniform and independent of the item structure. A weak hash that never sets high bits collapses the leading-zero statistic. The algorithm estimates cardinality. It does not estimate frequencies. A heavy-hitter sketch is count-min.<\/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>Choose p and set m = 2^p. Allocate m registers, initially zero.<\/li>\n<li>For each item, hash it to a wide integer. Use the top p bits as the bucket index. Count the leading zeros in the remaining bits and add one. Store the maximum of that value and the register.<\/li>\n<li>At query time, compute the harmonic raw estimate \u03b1_m \u00b7 m\u00b2 \u00b7 (sum over registers of 2^{\u2212register})^{\u22121}, with \u03b1_m the usual bias constant.<\/li>\n<li>If many registers are zero, or the estimate is huge relative to 2^{32} or the hash width, apply the small-range or large-range correction the implementation documents.<\/li>\n<li>To merge two sketches, take the maximum of each register pair.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The relative-error formula is for the raw estimator in its intended range, with uniform hashes. It is not an exact distinct count, and it is not a frequency. Small-range correction is part of a correct library implementation. Quoting 1.04\/sqrt(m) for a sketch that skipped that correction misstates the error on a tiny set.<\/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 registers are averaged arithmetically<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Take the arithmetic mean of the registers<\/td>\n<td>The statistic is a maximum of geometric variables. The harmonic mean of the powers of two is the estimator that has the stated variance. An arithmetic mean is a different, biased formula.<\/td>\n<\/tr>\n<tr>\n<td>Store the items and also keep the registers, then report the register estimate as exact<\/td>\n<td>The registers never become exact. If the items are stored, report the set size and skip the sketch.<\/td>\n<\/tr>\n<tr>\n<td>Merge by adding registers<\/td>\n<td>The maximum leading-zero count of a union is the max of the counts, not the sum. Adding double-counts the same hash range.<\/td>\n<\/tr>\n<tr>\n<td>Use a 32-bit hash for a cardinality near 2^32<\/td>\n<td>The leading-zero statistic saturates. The hash width has to exceed the range where the large-cardinality correction would dominate.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Membership is a Bloom filter. Frequencies are a count-min sketch. Exact distinct counting is a hash set. HyperLogLog is the cardinality sketch.<\/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 hashes each item into one of 64 registers and keeps the longest run of leading zeros. The harmonic estimate, with the small-range correction when many registers are still zero, is the cardinality. One hundred distinct items, hashed into 1024 registers, estimate as <code>102<\/code> after the small-range correction.<\/p>\n\n<pre><code class=\"language-python\">import math\np = 10\nm = 1 &lt;&lt; p\nregisters = [0] * m\n\ndef hash32(item):\n    x = (item + 0x9E3779B9) &amp; 0xFFFFFFFF\n    x = ((x ^ (x &gt;&gt; 16)) * 0x85EBCA6B) &amp; 0xFFFFFFFF\n    x = ((x ^ (x &gt;&gt; 13)) * 0xC2B2AE35) &amp; 0xFFFFFFFF\n    return (x ^ (x &gt;&gt; 16)) &amp; 0xFFFFFFFF\n\nfor item in range(100):\n    hashed = hash32(item)\n    bucket = hashed &gt;&gt; (32 - p)\n    rest = hashed &amp; ((1 &lt;&lt; (32 - p)) - 1)\n    rank = (32 - p + 1) if rest == 0 else ((32 - p) - rest.bit_length() + 1)\n    registers[bucket] = max(registers[bucket], rank)\nalpha = 0.7213 \/ (1 + 1.079 \/ m)\nraw = alpha * m * m \/ sum(2.0 ** (-rank) for rank in registers)\nzeros = registers.count(0)\nestimate = m * math.log(m \/ zeros) if zeros and raw &lt;= 2.5 * m else raw\nassert zeros and abs(estimate - 100) &lt; 5\nprint(round(estimate))\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>Redis <code>PFCOUNT<\/code><\/strong> and the approximate distinct-counts in warehouse engines are HyperLogLog. A dashboard of unique visitors uses it so the counter stays a few kilobytes. An exact set is the replacement when the error bar is unacceptable.<\/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 the sketch when the set fits in memory and an exact count is required. Keep it when a relative error near 1\/sqrt(m) is acceptable and the stream of distinct items does not fit, and merge sketches by the register-wise maximum.<\/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 HyperLogLog returns the leading-zero registers, the harmonic estimate, and the relative error 1.04\/sqrt(m). <strong>HyperLogLog estimates set cardinality from the maximum leading-zero count in each hash bucket, with relative error about 1.04 over the square root of the number of buckets.<\/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: HyperLogLog estimates the number of distinct items in a stream from the position of the first 1-bit in each item&#8217;s hash. Items are bucketed by the first p bits of the hash, into m = 2^p registers. Each register stores the maximum number of leading zeros, plus&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,36],"tags":[],"class_list":["post-194","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-sketches"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/194","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=194"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/194\/revisions"}],"predecessor-version":[{"id":593,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/194\/revisions\/593"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=194"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=194"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}