Counting by Occasionally Incrementing
An exact counter adds one for every event. Morris counting asks a stranger question: what if the stored counter advances less often as it grows? Early increments happen frequently; later increments are rare. The state is then best read as an exponent rather than as the count itself.
Imagine a notebook with numbered milestones. At state $C=0$, record the next arrival with probability $1$. At $C=1$, record an arrival with probability $1/2$; at $C=2$, with probability $1/4$; and so on. For base $b=2$, the decoded estimate is $2^C-1$. States $0,1,2,3,4$ represent estimates $0,1,3,7,15$. One stored increment covers an increasingly large interval of real arrivals.
This deep dive builds on approximate counting and sampling. The prerequisite chapter introduces the idea that randomized sampling can trade precision for space. Morris counting resolves a sharper question: how can the counter itself represent totals far larger than its numeric state, and why does the exponential decoder remain unbiased despite random skipped updates?
The algorithm maintains an integer state $C$, initially zero. For each unit-weight event, it increments $C$ with probability $b^{-C}$, where $b\gt1$. Its estimate is
$$ \widehat n(C)=\frac{b^C-1}{b-1}. $$
For $b=2$, suppose random draws for four arrivals are $0.40,0.70,0.10,0.30$. The first arrival certainly raises $C$ from 0 to 1. At $C=1$, the second draw $0.70$ misses the threshold $1/2$. The third draw $0.10$ succeeds and raises $C$ to 2. At $C=2$, the fourth draw $0.30$ misses the threshold $1/4$. The final state $C=2$ decodes to $3$, although four events occurred. A single realization need not be exact; unbiasedness concerns the average over the algorithm's randomness.
Important vocabulary follows from this mechanism. A probabilistic increment is the Bernoulli decision made per arrival. Exponential decoding maps the small state back to the count scale. An unbiased estimator has expectation equal to the true count, not zero error on every run. Variance measures spread across independent runs. Rescaling changes the base or combines several counters to trade state range, update work, and accuracy. Saturation occurs when the stored state reaches its largest representable value and can no longer advance correctly.
Why this matters is the double logarithm. After $n$ events, the typical state is about $\log_b n$. Storing a number of that magnitude takes about $\log_2\log_b n$ bits. A tiny state can therefore span enormous totals, although real implementations must also store randomness state, protect against overflow, and tolerate substantial estimator variance.
Morris counting stores a logarithm of the count and compensates for increasingly rare state changes with exponential decoding. Its estimate is unbiased in expectation, but one counter is noisy, is not an exact event total, and cannot safely be updated with arbitrary weights by simply treating each weighted record as one event.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Main assumption | Question answered |
|---|---|---|---|---|---|
| Probabilistic increment | Store only a random fraction of arrivals | At $C=3,b=2$, increment with probability $1/8$ | Increment every eighth event deterministically | Fresh uniform draw per event | How does state growth slow down? |
| Exponential decoder | Translate state back to count scale | $C=4,b=2$ gives $2^4-1=15$ | Reporting $C=4$ as four events | Same base used for update and decode | What total does a state represent? |
| Unbiasedness | Average estimate equals true count | $\mathbb E[\widehat n_t]=t$ | Every run equals $t$ | Correct transition probabilities and no saturation | Is systematic error zero? |
| Variance | Spread caused by skipped increments | Base two gives $t(t-1)/2$ | Absolute error guarantee for one run | Independent random trials under the model | How noisy is one counter? |
| Base $b$ | Tunes probability and decoded spacing | $b=1.1$ gives finer states than $b=2$ | Choosing $b=1$ in the formula | $b\gt1$ and numerically stable arithmetic | How are range and variance traded? |
| Confidence amplification | Combine independent counters | Average reduces variance by factor $r$ | Duplicating one random stream $r$ times | Independent counter randomness | How can reliability improve? |
| Saturation | State cannot represent another level | 8-bit $C=255$ is held fixed | Floating-point display overflow alone | Finite state representation | When does the estimator cease to be unbiased? |
Counting by Occasionally Incrementing
Use base $b=2$, initial state $C=0$, and uniform draws $0.40,0.70,0.10,0.30,0.20$ for five arrivals.
- Arrival 1: threshold $2^0=1$; $0.40\lt1$, so $C=1$ and estimate $1$.
- Arrival 2: threshold $2^{-1}=0.5$; $0.70$ misses, so $C=1$.
- Arrival 3: $0.10\lt0.5$, so $C=2$ and estimate $3$.
- Arrival 4: threshold $2^{-2}=0.25$; $0.30$ misses, so $C=2$.
- Arrival 5: $0.20\lt0.25$, so $C=3$ and estimate $7$.
Expected result: five actual arrivals produce state 3 and estimate 7 on this random path. The error is allowed; unbiasedness emerges across repeated independent executions. Reflection: why would reusing the same deterministic draws across all replicated counters weaken confidence amplification?
Exponential States and an Unbiased Decoder
Fix a base $b\gt1$. Let $C_t$ be the state after $t$ unit arrivals and define $Y_t=b^{C_t}$. Conditional on $C_t=c$, the next state is $c+1$ with probability $b^{-c}=1/Y_t$ and remains $c$ otherwise. If the increment happens, $Y_t$ is multiplied by $b$.
The decisive calculation conditions on the current state:
$$ \mathbb E[Y_{t+1}\mid Y_t] =\frac1{Y_t}(bY_t)+\left(1-\frac1{Y_t}\right)Y_t =Y_t+(b-1). $$
Taking total expectation removes the conditioning:
$$ \mathbb E[Y_{t+1}]=\mathbb E[Y_t]+(b-1). $$
Because $Y_0=b^0=1$, induction gives $\mathbb E[Y_t]=1+t(b-1)$. Therefore
$$ \widehat n_t=\frac{Y_t-1}{b-1}=\frac{b^{C_t}-1}{b-1} \quad\Longrightarrow\quad \mathbb E[\widehat n_t]=t. $$
Nothing was approximated in this proof. Its obligations are precise: unit arrivals; exact increment probability $b^{-C_t}$; fresh randomness with the required conditional distribution; initial state zero; matched update and decoder bases; no saturation; and arithmetic capable of representing or safely approximating the probability and decoded value.
The memory claim follows from scale. Since the decoded magnitude near state $C$ is about $b^C$, representing totals near $n$ needs $C=\Theta(\log_b n)$. An ordinary binary register storing $C$ therefore needs $\Theta(\log\log n)$ bits. This counts the counter state, not a random-number generator, metadata, replicated counters, or machine alignment.
A counterexample makes the correction visible. Reporting $b^C$ instead of $(b^C-1)/(b-1)$ has expectation $1+t(b-1)$, not $t$. For $b=2$, $2^C$ overestimates by one in expectation. An exact integer counter is the nearby alternative: it has zero variance and supports straightforward merge by addition, but requires $\Theta(\log n)$ state bits rather than $\Theta(\log\log n)$.
flowchart TD
A[State C starts at zero] --> B[Define Y = b to power C]
B --> C[Increment with probability 1 divided by Y]
C --> D[On success Y becomes bY]
D --> E[Conditional expected change is b minus 1]
E --> F[Iterate expectation for t arrivals]
F --> G[E of Y is 1 plus t times b minus 1]
G --> H[Decode Y minus 1 over b minus 1]
H --> I[Unbiased estimate of t]
C --> X{Probability exact and unsaturated?}
X -->|no| Y[Invariant breaks and bias appears]
X -->|yes| D
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,C navy;
class D,E,F purple;
class G,H,I teal;
class X,Y crimson;
The proof works because the transformed state $Y=b^C$ gains $(b-1)Y$ with probability $1/Y$, making its conditional expected gain exactly $b-1$ at every level. Decoding removes the initial 1 and this scale factor; saturation, probability rounding, or a mismatched base destroys the invariant.
Variance, Rescaling and Counter Saturation
Unbiasedness does not imply concentration. To quantify noise, square the transformed state. Conditional on $Y_t$,
$$ \mathbb E[Y_{t+1}^2\mid Y_t] =Y_t^2+(b^2-1)Y_t. $$
Using $\mathbb E[Y_t]=1+t(b-1)$ and summing the recurrence gives
$$ \mathbb E[Y_t^2] =1+(b^2-1)\left[t+\frac{(b-1)t(t-1)}2\right]. $$
After subtracting $\mathbb E[Y_t]^2$ and dividing by $(b-1)^2$, the decoded estimator has
$$ \operatorname{Var}(\widehat n_t)=\frac{b-1}{2}t(t-1). $$
For large $t$, one counter's relative standard deviation approaches $\sqrt{(b-1)/2}$. Base two therefore approaches about $70.7\%$, much too noisy for many production metrics. Averaging $r$ independent counters preserves unbiasedness and divides variance by $r$; the relative standard deviation approaches $\sqrt{(b-1)/(2r)}$. Robust grouping and median amplification can convert a constant-probability accuracy statement into higher confidence, at additional memory and update cost.
Choosing $b$ closer to one lowers variance but pushes the state higher: $C\approx\log_b((b-1)n+1)$. This may require more state bits and causes more accepted increments. The base is therefore a three-way control over accuracy, state range, and update behavior.
Saturation is not harmless clipping. If the maximum state is $C_{\max}$, then once it is reached, the transition that underpins the expectation recurrence disappears. The estimator becomes capped at $(b^{C_{\max}}-1)/(b-1)$ and increasingly biased downward. Probability underflow can create an earlier effective saturation if $b^{-C}$ rounds to zero; decoder overflow can create an infinite or invalid result even while the state remains valid.
Variance, Rescaling and Counter Saturation
Take $b=2$, $t=1000$ events, and one Morris counter.
- Unbiased estimate: $\mathbb E[\widehat n]=1000$.
- Variance: $1000\cdot999/2=499{,}500$.
- Standard deviation: $\sqrt{499{,}500}\approx706.75$, or about $70.7\%$ relative standard deviation.
- Average $r=100$ independent counters. Variance becomes $4{,}995$, standard deviation about $70.68$, and relative standard deviation about $7.07\%$.
- Exact dynamic programming over states provides an independent check of the mean and variance; simulation should approach the same values within sampling error.
Perturbed base: with $b=1.08$ and $r=10$, asymptotic relative standard deviation is $\sqrt{0.08/20}\approx6.32\%$. The typical state is larger than for base two, so verify state width and probability precision before selecting it.
Saturation case: a 4-bit state has $C_{\max}=15$. At base two its maximum decoded estimate is $32{,}767$; after saturation, further arrivals cannot preserve unbiasedness.
| Variant | Assumptions | Accuracy or guarantee | State and update cost | Strength | Failure mode | Prefer when |
|---|---|---|---|---|---|---|
| Exact integer counter | Valid integer arithmetic | Zero estimation error before overflow | $\Theta(\log n)$ bits; one add | Simple, mergeable by addition | Integer overflow | Exact totals or ordinary word counters are affordable |
| One Morris counter, $b=2$ | Unit events, correct fresh randomness, no saturation | Unbiased; variance $n(n-1)/2$ | $\Theta(\log\log n)$ state bits | Extreme range from tiny state | About $70.7\%$ asymptotic relative SD | Teaching or very loose telemetry |
| Tuned-base Morris | Same, with stable real-base probabilities | Relative SD approaches $\sqrt{(b-1)/2}$ | Higher state and more accepted increments as $b$ approaches 1 | Direct accuracy-range tuning | Probability rounding or larger state | Moderate accuracy under severe state constraints |
| Average of $r$ counters | Independent counter randomness | Variance divided by $r$ | $r$ states and $r$ trials per event | Unbiased with predictable variance reduction | Correlated random streams | Mean-square error is primary |
| Median/grouped amplification | Independent groups and a valid constant-success bound | Failure probability decreases exponentially in groups | Multiple counters plus aggregation | High-confidence robustness | Wrong grouping or shared failures | Tail confidence matters more than unbiased aggregate |
| Deterministic sampled/exact hybrid | Defined sampling threshold and exact low range | Exact early counts, approximate later counts | Extra mode and metadata | Avoids poor small-count behavior | Transition bugs and merge complexity | Product metrics spanning tiny and huge totals |
Tiny Counters for Massive Event Totals
In a teaching setting, Morris counting makes expectation tangible. Students can trace a small random sequence, then derive why rare large jumps yield constant expected progress. Comparing one path with an exact state distribution prevents the common mistake of interpreting unbiasedness as pathwise accuracy.
At professional scale, imagine billions of low-value per-key diagnostic counters on constrained devices or in a dense telemetry table. Saving even a few bytes per key can matter. A tuned base and replicated counters may estimate large totals while using tiny state. The design must include a small-count policy, random-stream isolation, saturation telemetry, versioned base parameters, and empirical calibration against exact shadow counters.
The failure case is equally important. Billing, rate-limit enforcement, inventory, financial ledgers, and safety-event totals usually require exact or one-sided guarantees; an unbiased but highly variable counter is inappropriate. Adversaries may also exploit predictable random-number streams or send enough events to saturate state. Dropped events before the counter are not sampling noise and are not repaired by unbiased decoding.
Merging is subtle. Two independent Morris states cannot generally be added or decoded-and-added while retaining the distribution of a single counter over the combined stream. Safe distributed designs need a proven merge procedure, preserve sufficient replicated state, or aggregate exact/local counts before applying a counter at a defined boundary. “Both estimates are unbiased” only implies their numerical sum is an unbiased estimate of the sum; it does not make the summed state a valid Morris state for future updates.
Evidence that invalidates deployment includes sustained calibration bias, variance above the formula, cross-counter correlation, probability underflow, unexpected state saturation, incompatible base or RNG versions, failed merge invariants, and unacceptable error in decision-critical subgroups.
flowchart TD
A[Define decision and tolerated error] --> B{Exact counter affordable?}
B -->|yes| C[Use exact counter]
B -->|no| D[Choose base state width and replicas]
D --> E[Verify maximum decoded range]
E --> F[Validate RNG independence and arithmetic]
F --> G[Replay representative and hostile streams]
G --> H{Bias variance and saturation acceptable?}
H -->|no| I[Reject resize or use hybrid]
H -->|yes| J[Deploy with exact shadow sample]
J --> K[Monitor calibration correlation and state headroom]
K --> L{Assumption or SLO breach?}
L -->|yes| I
L -->|no| K
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,C navy;
class D,E,F,G purple;
class J,K teal;
class H,I,L crimson;
Tiny Counters for Massive Event Totals: Morris Approximate Counting
Scenario. An edge fleet tracks 50 million low-priority diagnostic categories. Counts may reach $10^{12}$ per category. The product tolerates about $5\%$ relative standard deviation for aggregate trend dashboards, but not for billing or alert thresholds. Updates must remain constant time, and devices report saturation telemetry.
- Parameter calculation: for averaged counters, asymptotic relative variance is approximately $(b-1)/(2r)$. With $b=1.05$ and $r=10$, relative SD is $\sqrt{0.05/20}=5\%$.
- Range check: solve $C\approx\log_{1.05}(1+0.05\cdot10^{12})\approx505$. A 10-bit state can hold values through 1023, leaving substantial headroom. Include numeric checks using the actual decoder representation.
- Memory accounting: ten 10-bit logical states require 100 bits per category before packing, alignment, RNG metadata, keys, and monitoring fields. Compare this full cost with a 40-bit exact counter and with sparse storage; the approximate design may lose once replication overhead is counted.
- Validation protocol: generate deterministic golden traces; compare exact dynamic-programming moments for small $n$; simulate production ranges; maintain exact shadow counts for sampled categories; inject correlated RNG seeds, state corruption, replayed events, maximum-state saturation, and probability underflow.
- Expected observations: mean residual remains near zero before saturation; sample variance approaches the derived formula; averaging helps only with independent streams; clipping creates increasing negative bias.
- Invalidation evidence: more than $1\%$ sustained calibration bias, relative SD above $5.5\%$, material replica correlation, any unreported saturation, or total packed memory exceeding the exact alternative.
Selection decision: use Morris counters only for lossy trend telemetry after the complete packed-memory comparison passes. Keep exact counters for billing and alerts, version every base/RNG encoding, and fall back or widen state when headroom alarms fire.
Implement and Calibrate Morris Counting
Mastery combines an exact expectation proof with implementation skepticism. The recurrence is short, yet production correctness depends on event semantics, floating-point behavior, random streams, state width, and aggregation. A good implementation exposes these choices rather than hiding them behind a function named increment.
The conceptual bridge backward is Bernoulli sampling and conditional expectation. The bridge forward leads to probabilistic data structures, stochastic averaging, confidence amplification, mergeable summaries, and floating-point-like encodings. Morris counting is especially useful as a lesson in co-design: the state transition and decoder are mathematically inseparable.
Practice: Implement and Calibrate Morris Counting
Starter configuration: base $b=1.25$, $n=10{,}000$ unit events, $r=20$ independent replicas, and a 7-bit state with maximum $127$.
Tier 1 — Trace and decode
- Starting at $C=0$, trace six arrivals using uniforms $0.20,0.90,0.30,0.60,0.10,0.80$.
- At each step record $C$, threshold $b^{-C}$, accepted/skipped status, and decoded estimate.
- Verify that the estimate changes only when state changes.
Expected artifact: a six-row table. Completion criterion: every threshold is computed from the pre-update state.
Tier 2 — Reconstruct the proof
Derive $\mathbb E[Y_{t+1}\mid Y_t]=Y_t+b-1$ for $Y_t=b^{C_t}$, then prove unbiasedness by induction. Derive the second-moment recurrence and simplify it to $\operatorname{Var}(\widehat n_t)=(b-1)t(t-1)/2$.
Debugging prompt: if the expected gain contains $Y_t$, recheck the multiplication of jump size by increment probability.
Tier 3 — Size accuracy and range
- Predict one-counter relative SD for large $n$: $\sqrt{0.25/2}\approx35.36\%$.
- Predict averaged relative SD for $r=20$: $\sqrt{0.25/40}\approx7.91\%$.
- Estimate required state $C\approx\log_{1.25}(1+0.25n)$ and compare with 127.
- Include state packing, RNG state, and replica count when comparing with an exact counter.
Tier 4 — Verify and break it
Run exact dynamic programming for small $n$ and deterministic simulation for $n=10{,}000$. Add tests for zero events, $b=1$, negative events, state saturation, probability underflow, identical seeds across replicas, and a decoder using the wrong base.
Expected artifacts: mean/variance comparison, confidence interval for simulation error, and a failure table. Completion criterion: every deliberate defect is detected by an assertion or monitor.
Tier 5 — Professional judgment
Choose among exact, one Morris counter, tuned-base replicas, or a hybrid for: page-view trends, financial transactions, and embedded diagnostic categories. State the accepted error, memory including overhead, update budget, merge semantics, threat model, and evidence that would reverse the choice.
Stretch goal: design a safe small-count hybrid that remains exact through a threshold and transitions to Morris state. Prove or empirically calibrate the transition rather than assuming the original unbiasedness proof still applies.
Rubric (10 points): trace correctness 2; expectation and variance derivations 2; executable verification 2; boundary/failure handling 2; operational selection 2. Mastery requires at least 8 points and explicit rejection of Morris counting for an unsuitable exactness-critical case.
Reflection: after accounting for replicas, random-number state, and alignment, is the approximate counter still smaller than the exact alternative?
Decision checklist: confirm unit-event semantics, match update probability and decoder base, derive variance for the chosen $b$, include replica/RNG overhead, reserve saturation headroom, validate independent streams, and monitor against exact shadows. Do not confuse unbiasedness with low error or assume Morris states merge by addition; the next step is learning when richer sketches provide the accuracy, mergeability, and query semantics that counting alone cannot.