Proving Programs Correct with Invariants
Tests show that a program works on the inputs you tried. A proof shows it works on all of them. For loops, the tool is the loop invariant, the program version of the invariant principle and of induction. Writing invariants down, even informally as comments or assert statements, is one of the most effective ways to write correct algorithms such as binary search, which is notoriously easy to get subtly wrong.
The method
A loop invariant is a statement about the program's variables that
- Initialization: holds before the first iteration,
- Maintenance: if it holds before an iteration, it holds after it,
- Termination: when the loop stops, the invariant plus the exit condition imply the result you want.
Add a variant (a non-negative integer that decreases every iteration) to prove the loop stops.
Example 1: summing a list
def total(xs):
s, i = 0, 0
# invariant: s == sum(xs[:i])
while i < len(xs):
assert s == sum(xs[:i])
s += xs[i]
i += 1
# exit: i == len(xs), so s == sum(xs)
return s
print(total([3, 1, 4, 1, 5, 9, 2, 6]))31
Initialization: is the sum of the empty prefix. Maintenance: adding extends the prefix by one. Termination: gives the whole sum. Variant: .
Example 2: binary search
def binary_search(a, target):
"""a is sorted. Returns an index of target, or -1."""
lo, hi = 0, len(a)
# invariant: if target is in a, it is in a[lo:hi]
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1 # everything up to mid is < target
elif a[mid] > target:
hi = mid # everything from mid on is > target
else:
return mid
return -1 # a[lo:hi] is empty, so target is not in a
a = [2, 3, 5, 7, 11, 13, 17, 19, 23]
print([binary_search(a, t) for t in [2, 7, 23, 4, 30]])
import random
rng = random.Random(1)
ok = True
for _ in range(2000):
arr = sorted(rng.sample(range(100), rng.randint(0, 20)))
t = rng.randrange(-5, 105)
r = binary_search(arr, t)
ok &= (r == -1 and t not in arr) or (r >= 0 and arr[r] == t)
print("random tests passed:", ok)[0, 3, 8, -1, -1]
random tests passed: True
Maintenance: if , then because is sorted, every with is smaller than the target, so the target (if present) is in . Symmetrically for the other branch. Termination: the variant strictly decreases each iteration (since ), so the loop ends; when the range is empty and the invariant says the target is absent.
The invariant also explains the classic bugs. Writing hi = mid - 1 with a half-open range a[lo:hi] would skip index ; writing lo = mid could loop forever when (the variant would not decrease).
Example 3: Euclid's algorithm
from math import gcd
def euclid(a, b):
a0, b0 = a, b
while b != 0:
assert gcd(a, b) == gcd(a0, b0) # invariant
a, b = b, a % b # variant: b decreases
return a
print(euclid(1071, 462), euclid(17, 5), euclid(0, 9))21 1 9
The invariant is the key lemma of the GCD lesson; at exit and .
Partial and total correctness
- Partial correctness: if the program terminates, its answer is right (invariant).
- Total correctness: partial correctness plus termination (variant).
Some loops are partially correct but never shown to terminate: the Collatz loop while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 has been checked for enormous ranges of starting values, but nobody has proved it always stops.
In software
Tools such as Dafny, Why3, Frama-C and SPARK Ada check invariants and variants automatically; Amazon, Microsoft and others use them for security-critical code. In everyday code, assert statements for invariants, written once and run in tests, catch bugs at the moment the reasoning breaks rather than much later. Property-based testing tools check invariants on thousands of random inputs.
Exercises
Exercise 1: Find the invariant
What is an invariant for this loop, and what does it compute? p, i = 1, 0 then while i < n: p *= x; i += 1.
Answer
; it computes .
Solution
Initially . Each iteration multiplies by and increases by 1, preserving . At exit , so . The variant is .
Exercise 2: A bug
Someone changes binary search to lo = mid instead of lo = mid + 1. Find an input that makes it loop forever.
Answer
a = [1, 3] with target = 5: any search where lo must move past mid when .
Solution
With a = [1, 3] and target = 5: , , , so . Now , , again, and stays 1 forever. The variant did not decrease, which is exactly the termination argument failing.
Exercise 3: Insertion sort invariant (code)
Add an assertion for the invariant "the prefix a[:i] is sorted" to insertion sort and run it on random lists.
Answer
The assertion never fails, and the output is sorted.
Solution
import random
def insertion_sort(a):
a = list(a)
for i in range(1, len(a)):
assert all(a[k] <= a[k + 1] for k in range(i - 1)) # invariant: a[:i] is sorted
x, j = a[i], i - 1
while j >= 0 and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return a
rng = random.Random(2)
print(all(insertion_sort(xs) == sorted(xs) for xs in ([rng.randint(0, 50) for _ in range(rng.randint(0, 30))] for _ in range(500))))True
Test yourself
Which three properties make a loop invariant useful for a correctness proof?
- Speed, memory, clarity
- Initialization, maintenance, and usefulness at termination
- Base case, step, conclusion of a recursion
- Reflexive, symmetric, transitive
What proves that a loop terminates?
- An invariant
- A non-negative integer quantity that strictly decreases each iteration
- Testing
- A comment
In binary_search with the half-open range a[lo:hi], what is the invariant?
lo == hi- if the target is in
a, it is ina[lo:hi] a[mid] == targethi - lois even