TExcelTAD
Home › Discrete Mathematics › Proving Programs Correct with Invariants

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

  1. Initialization: holds before the first iteration,
  2. Maintenance: if it holds before an iteration, it holds after it,
  3. 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

python · try it yourself
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: s=0s = 0 is the sum of the empty prefix. Maintenance: adding xix_i extends the prefix by one. Termination: i=ni = n gives the whole sum. Variant: n−in - i.

Example 2: binary search

python · try it yourself
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 a[mid]<targeta[mid] < target, then because aa is sorted, every a[j]a[j] with j≤midj \le mid is smaller than the target, so the target (if present) is in a[mid+1:hi]a[mid+1 : hi]. Symmetrically for the other branch. Termination: the variant hi−lohi - lo strictly decreases each iteration (since lo≤mid<hilo \le mid < hi), so the loop ends; when lo=hilo = hi 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 mid−1mid - 1; writing lo = mid could loop forever when hi=lo+1hi = lo + 1 (the variant would not decrease).

Example 3: Euclid's algorithm

python · try it yourself
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 gcd⁡(a,b)=gcd⁡(a0,b0)\gcd(a, b) = \gcd(a_0, b_0) is the key lemma of the GCD lesson; at exit b=0b = 0 and gcd⁡(a,0)=a\gcd(a, 0) = a.

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

p=xip = x^i; it computes xnx^n.

Solution

Initially p=1=x0p = 1 = x^0. Each iteration multiplies pp by xx and increases ii by 1, preserving p=xip = x^i. At exit i=ni = n, so p=xnp = x^n. The variant is n−in - i.

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 hi=lo+1hi = lo + 1.

Solution

With a = [1, 3] and target = 5: lo=0lo = 0, hi=2hi = 2, mid=1mid = 1, a[1]=3<5a[1] = 3 < 5 so lo=1lo = 1. Now lo=1lo = 1, hi=2hi = 2, mid=1mid = 1 again, and lolo stays 1 forever. The variant hi−lohi - lo 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
python · try it yourself
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?

  1. Speed, memory, clarity
  2. Initialization, maintenance, and usefulness at termination
  3. Base case, step, conclusion of a recursion
  4. Reflexive, symmetric, transitive

What proves that a loop terminates?

  1. An invariant
  2. A non-negative integer quantity that strictly decreases each iteration
  3. Testing
  4. A comment

In binary_search with the half-open range a[lo:hi], what is the invariant?

  1. lo == hi
  2. if the target is in a, it is in a[lo:hi]
  3. a[mid] == target
  4. hi - lo is even