Download and extract the reader ZIP archive (a compressed collection of files). Links labelled โreader ZIP; extract โฆโ download this archive; after extraction, open the named file. It includes the offline article, full-size Portable Network Graphics (PNG) images, editable Scalable Vector Graphics (SVG) diagrams, complete source code, tests and worksheets.
Timing and digital arithmetic ยท constructed experiment
A counter can cross zero safely and still lose the information needed to tell which reading came later. Build a small executable model, force the ambiguous cases, and choose the observation contract before trusting a subtraction.
Verification scope: This is a paper and Python experiment with invented integer counts. It reads no timer, drives no circuit and measures no elapsed seconds. The supplied tests run on a normal computer and exercise the model; code built or run for a particular electronics board and physical measurements are not claimed.
What the experiment needs
A counter is a stored number that advances when events occur. A tick is one such increment; its duration is deliberately unspecified here. A finite counter eventually runs out of representable values and returns to zero. That return is wraparound. We use an eight-bit counter, meaning eight binary digits store 256 possible values, from 0 through 255. Its modulus, written M, is 256: values repeat after every 256 ticks.
The stored reading is a residue, the remainder after division by M. It is not a complete lifetime tick count. If an imagined unlimited counter reads U, its stored reading is U mod M. Here โmodโ means take the nonnegative remainder. A residue tells you where the counter is within one turn; it does not tell you how many turns have passed.
Use a computer with Python 3.9 or later and a text editor. The delivered run was made with Python 3.9.6. No third-party library is needed for the model or tests. The component list is therefore software only: wrapping_counter.py calculates conditional differences and maintains an accumulated total; test_wrapping_counter.py checks wrap, limits, ambiguity and recovery. No hardware, pin connections or electrical supply is applicable to this experiment.
Start with a wrap that subtraction can repair
Suppose the earlier reading is 250 and the later reading is 3. Ordinary subtraction gives 3 โ 250 = โ247, while the imagined counter advanced nine ticks: 251, 252, 253, 254, 255, 0, 1, 2, 3. Modular subtraction computes a nonnegative difference:
d = (now โ previous) mod M = (3 โ 250) mod 256 = 9.
The result is useful only with an additional statement: the true forward gap g was less than M, and the counter advanced monotonically without a reset. โMonotonicallyโ here means that the underlying unlimited count never moved backward. Under those conditions g is one of 0 through 255, and exactly one of those integers has residue d. Therefore g = d.
There is no need for a half-turn bound when you already know the direction and only recover a nonnegative elapsed count. A true forward gap of 255 is recoverable from two readings if a truthful external bound rules out 256 or more. This is a different operation from deciding the signed direction between two arbitrary readings.
โ reader ZIP; extract assets/counter-residue-aliases.pngassets/counter-residue-aliases.svg; full-size image โ reader ZIP; extract assets/counter-residue-aliases.png.The same residue does not prove the same instant
Now allow a longer pause. Starting from 250, gaps of 9, 265 and 521 ticks all end at 3, because each differs by a whole multiple of 256. In general, the possible nonnegative gaps are d, d + M, d + 2M and so on. The two readings alone cannot choose among them. Looking at a perfectly reasonable small result does not prove the pause was short.
The especially deceptive case is 7 followed by 7. It may mean zero elapsed ticks, 256 ticks, 512 ticks or more. The experimentโs elapsed_forward function accepts zero when an external upper bound is 255, because that bound excludes a full turn. It refuses the same readings when the upper bound reaches 256. Refusal means โthe elapsed count is unknown under this contract,โ not โthe elapsed count is zero.โ
| Previous โ now | Constructed true gap | Independent upper bound | Forward result |
|---|---|---|---|
| 250 โ 3 | 9 | 10 | 9 ticks |
| 7 โ 7 | 0 | 255 | 0 ticks |
| 7 โ 7 | 256 | 256 | Unknown |
| 250 โ 3 | 521 | 521 | Unknown |
| 10 โ 9 | 255 | 255 | 255 ticks |
Signed ordering has the stricter half-turn limit
A signed difference can be positive or negative. It is useful when the question is โhow far after or before this reference is the other event?โ A common rule chooses the shortest route around the counter ring. First calculate d in 0 through M โ 1. If d is below M/2, return d; if d is above M/2, return d โ M. The exact halfway value has two equally short routes and cannot supply an unambiguous direction.
For M = 256: signed d is d when 0 โค d โค 127, and d โ 256 when 129 โค d โค 255. A residue difference of 128 is direction-ambiguous.
This rule identifies the true signed displacement only when its magnitude is less than M/2. For this integer counter, the allowed interval is โ127 through +127, inclusive. A signed result of +9 can describe 250 โ 3 across zero; โ9 describes the reverse comparison. But a true forward displacement of +137 from 250 ends at 131, and the shortest-route rule returns โ119. Both displacements have the same residue. The function cannot discover that the caller lied about a short separation.
The supplied signed comparator requires an explicit max_separation smaller than 128. It also rejects residues inconsistent with that bound. Those checks catch some bad calls, including the exact halfway case. They cannot certify the bound itself. Passing 127 as a constant is a promise from the application, not a measurement performed by this function.

assets/counter-signed-horizon.svg; full-size image.Choose a gap contract you can actually justify
An observation gap is the time, or number of increments, between observations. An upper bound is a known maximum, not an average or typical value. In a real design, the bound must include every source of delay that can postpone an observation: lengthy processing, blocked input/output, sleep, debugging pauses and recovery after faults. Here the worksheet supplies that information explicitly because it is a constructed experiment.
Do not estimate the gap bound from the same modular subtraction whose validity you are trying to establish. That would assume the missing information. A separate trusted time base, a guaranteed service interval with a maximum tick rate, or a wider counter maintained without lost overflow events can establish a bound. Each approach has its own failure conditions. An interrupt that counts wraps is useful only if wraps cannot be missed and the combined read is coherent.
For scale, an ideal 32-bit counter ticking exactly once per millisecond has M = 2ยณยฒ = 4,294,967,296 ticks. One full turn would be about 49.71027 days; half a turn is about 24.85513 days. These are arithmetic conversions, not measured timer performance. A signed comparison needs a separation no larger than 2,147,483,647 ticks; known-forward elapsed recovery needs a gap no larger than 4,294,967,295 ticks. A real clockโs resolution, rate error, pauses and counter reset behavior require separate verification.
Frequent polling alone does not make an ancient reference safe. If you compare every new reading directly with a start value from several turns ago, that individual comparison has a long separation even if adjacent polls were close together. Accumulate valid adjacent differences, or retire deadlines before their comparison horizon is exceeded. A deadline is a planned counter value at which an action becomes due; both how far it is placed into the future and how late it may be checked matter.
Run the complete experiment
The supplied ZIP compressed reader archive contains this article, both originals, the full program, tests and worksheets. See the reader contents and reproduction instructions โ reader ZIP; extract README.txt. The figures are supplied as Scalable Vector Graphics (SVG), editable shapes and labels, and Portable Network Graphics (PNG), full-size pixel-based images. The standalone page uses Hypertext Markup Language (HTML) for structure and Cascading Style Sheets (CSS) for presentation. Data files use comma-separated values (CSV), one record per line.
- Extract the archive and open
standalone-preview.html. Keep its neighboring folders in place so local links work. - Open a terminal in the extracted folder. Run the commands below. This terminal use is a command-line interface (CLI): typed commands launch the program and show its output.
- Compare
constructed-cases.csvwith the table above. The โtrue gapโ column is deliberately supplied by the constructed case. It is not inferred from the readings. - Change the supplied programโs constructed list, or call its functions in a Python session. Use
data/blank-observations.csvto record the contract and result for each case. Never fill a missing true-gap field with the modular result and call it evidence.
python3 -m unittest discover -s code -v
python3 code/wrapping_counter.py > constructed-cases.csv
The suite checks all 16 starting residues and every forward gap below one turn for a smaller four-bit counter, plus all signed displacements from โ7 through +7. It also exercises the 256-count boundaries, invalid inputs, lost certainty, explicit restoration and an accumulated total beyond a 64-bit integer. Python integers expand to hold larger totals; fixed-width implementations need a separate overflow policy.
Complete model
GapError reports missing or inconsistent gap knowledge. The accumulator latches an invalid state after a failed update and refuses later updates until a trusted anchor is restored. An anchor is a known pairing of a residue and an accumulated total. Restoration does not recover counts that were lost during a pause; the caller must supply the total or deliberately begin a new counting epoch, meaning a new reference origin.
#!/usr/bin/env python3
"""Constructed finite-counter experiment; no real clock or board is read."""
import argparse
import csv
import sys
class GapError(ValueError):
"""Independent gap contract is absent, exceeded or inconsistent."""
def integer(value, name, minimum=0):
if type(value) is not int or value < minimum:
raise ValueError(name + ' must be an integer >= ' + str(minimum))
return value
def validate(now, previous, modulus):
integer(modulus, 'modulus', 2)
if modulus & (modulus - 1):
raise ValueError('modulus must be a power of two')
for value in (now, previous):
integer(value, 'counter reading')
if value >= modulus:
raise ValueError('counter reading is outside its modulus')
def elapsed_forward(now, previous, modulus, upper_bound):
"""Unique nonnegative gap if a truthful external bound is < one turn.
upper_bound is supplied knowledge, NEVER estimated from these readings.
The counter must advance monotonically, one count per tick, with no reset.
"""
validate(now, previous, modulus)
integer(upper_bound, 'upper_bound')
if upper_bound >= modulus:
raise GapError('gap could contain a full turn; elapsed count unknown')
delta = (now - previous) % modulus
if delta > upper_bound:
raise GapError('residues contradict the supplied upper bound')
return delta
def signed_delta(now, previous, modulus, max_separation):
"""Nearest signed difference, conditional on true |separation| < M/2."""
validate(now, previous, modulus)
integer(max_separation, 'max_separation')
half = modulus // 2
if max_separation >= half:
raise GapError('signed comparison requires a bound strictly below half a turn')
delta = (now - previous) % modulus
if delta == half:
raise GapError('exact half-turn has two equally short directions')
result = delta if delta < half else delta - modulus
if abs(result) > max_separation:
raise GapError('residues contradict the supplied separation bound')
return result
class BoundedCounter:
"""Accumulate adjacent known-forward readings; latch loss of certainty.
No timing source is implemented here. A real application must supply an
independently justified upper bound for every adjacent observation gap.
"""
def __init__(self, modulus, max_gap, initial, initial_total=0):
validate(initial, initial, modulus)
integer(max_gap, 'max_gap')
if max_gap >= modulus:
raise ValueError('max_gap must be less than modulus')
self.modulus = modulus
self.max_gap = max_gap
self.restore(initial, initial_total)
def update(self, current, gap_bound):
if not self.valid:
raise GapError('counter invalid: restore from a trusted external anchor first')
try:
integer(gap_bound, 'gap_bound')
if gap_bound > self.max_gap:
raise GapError('observation gap exceeds the configured contract')
delta = elapsed_forward(current, self.previous, self.modulus, gap_bound)
except ValueError:
self.valid = False
raise
self.total += delta
self.previous = current
return self.total
def restore(self, current, trusted_total):
"""Start a trusted epoch; does not reconstruct any lost counts."""
validate(current, current, self.modulus)
integer(trusted_total, 'trusted_total')
self.previous = current
self.total = trusted_total
self.valid = True
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--modulus', type=int, default=256)
args = parser.parse_args()
# This fixed worksheet intentionally uses an 8-bit model.
if args.modulus != 256:
parser.error('the constructed worksheet uses --modulus 256 only')
writer = csv.writer(sys.stdout, lineterminator='\n')
writer.writerow(['case', 'previous', 'now', 'true_forward_ticks', 'external_upper_bound', 'forward_result', 'signed_result_bound127'])
for name, old, gap, bound in [('ordinary',10,20,20),('wrap',250,9,10),('same_zero',7,0,255),('same_full_turn',7,256,256),('multiple_turns',250,521,521),('half_turn',10,128,128),('signed_wrong_if_contract_false',250,137,137),('last_forward_tick',10,255,255)]:
now = (old + gap) % 256
try:
forward = elapsed_forward(now, old, 256, bound)
except GapError as exc:
forward = 'UNKNOWN: ' + str(exc)
try:
signed = signed_delta(now, old, 256, 127)
except GapError as exc:
signed = 'UNKNOWN: ' + str(exc)
writer.writerow([name, old, now, gap, bound, forward, signed])
return 0
if __name__ == '__main__':
raise SystemExit(main())
Try a failure, then restore honestly
Create c = BoundedCounter(256, 100, 250). The configured maximum adjacent gap is 100 ticks. The call c.update(3, 9) returns 9. Now call c.update(4, 101): it fails because the independently supplied upper bound exceeds the configured service contract. The total remains 9 and the state becomes invalid. A later apparently short gap cannot repair that missing history.
For a paper recovery experiment only, call c.restore(4, 1000), asserting a trusted total of 1000 at residue 4. Then c.update(9, 5) returns 1005. The number 1000 came from you; it was not reconstructed from 4. In a real system you would need external retained state, a verified wider counter or a deliberate reset of the epoch. Keep unknown elapsed intervals marked unknown.
Challenge and answer
Challenge: A 256-count forward counter reads 200 and later 72. Can you report +128? Can you report which reading is later using a signed shortest-route comparison? What if the later reading were 73 and a separate source established that no more than 129 ticks passed?
Answer
With a truthful known-forward upper bound of 128, the first pair uniquely gives +128 because it is less than one full turn. A signed ordering comparison cannot choose between +128 and โ128 from that pair. For 200 โ 73, a known-forward bound of 129 gives +129. The signed shortest-route result would be โ127, so its half-turn contract would be false for that physical forward gap. Knowing direction and choosing an ordering direction are different questions.
References and further reading
Request for Comments (RFC) 1982, Serial Number Arithmetic, August 1996, sections 3.1โ3.2 is the primary protocol specification for finite serial-number ordering. Its protocol rules are a reference for the half-range comparison idea; the known-forward elapsed-count function here has its own explicitly stated one-turn contract.
MicroPython v1.26.0 time documentation gives a real timer-interface example with a bounded signed difference and warns about excessive separation. Use its documented ticks_diff and ticks_add operations on an actual MicroPython port rather than replacing them with this teaching model or guessing its counter period.
Continue through Tricky Circuit Learn or search Circuitpedia for supporting terminology. New terms proposed by this local package have not been added to the live dictionary.