Video lecture
Watch on YouTube(opens in a new tab)Sub topic 12
Loop Invariants as a Correctness Tool
This chapter assumes you already know how to write a specification with preconditions and postconditions, how to trace a loop with a state table, and what it means for an algorithm to be correct against its specification. Termination is covered in its own chapter, so it is mentioned here only where it connects to invariants.
Tracing tells you the algorithm works on one input. A loop invariant lets you argue that it works on every input that meets the precondition. It does this without running the loop at all.
What a Loop Invariant Is
A loop invariant is a statement about the program's variables that is true each time execution reaches the loop's test. That includes the first test, before the body has run, and the final test, when the condition fails and the loop exits.
The invariant does not have to hold in the middle of the body. While the body runs, variables are being updated one at a time, and the statement may be briefly false. It only has to be true again by the time control returns to the test.
A useful invariant does two things. It is true at every test, and it is strong enough that, combined with the fact that the loop has stopped, it gives you the postcondition.
The Three Obligations
To use an invariant I in a correctness argument, you show three things:
- Initialization. If the precondition holds, then
Iis true just before the first test. - Maintenance. If
Iis true and the loop condition is true at the start of an iteration, thenIis true again after the body runs. - Exit. If
Iis true and the loop condition is false, then the postcondition holds.
Initialization and maintenance together are an induction argument. The base case is the first test, and the inductive step is one pass through the body. The exit step turns the invariant into the result you promised.
Worked Example: Finding the Maximum
The specification for this example is:
- Precondition:
xsis a non-empty list of comparable values. - Postcondition: the returned value
bestequals the largest element ofxs.
An index-based loop makes the invariant easy to state exactly. The invariant is best == max(xs[:i]), which says that best is the largest of the first i elements.
def find_max_checked(xs):
assert len(xs) > 0 # precondition
best = xs[0]
i = 1
assert best == max(xs[:i]) # initialization
while i < len(xs):
if xs[i] > best:
best = xs[i]
i += 1
assert best == max(xs[:i]) # maintenance
assert i == len(xs) # loop condition is false
assert best == max(xs) # postcondition
return best
print(find_max_checked([3, 9, 2, 9, 4])) # 9Here is the argument for each obligation.
- Initialization. When
i = 1,xs[:1]is[xs[0]], andbestisxs[0]. The maximum of a one-element list is that element, so the invariant holds. - Maintenance. Assume
bestis the maximum ofxs[:i]andi < len(xs). The maximum ofxs[:i+1]is the larger ofmax(xs[:i])andxs[i]. Theifstatement setsbestto exactly that value. Thenigoes up by one, so the invariant holds for the newi. - Exit. The loop stops when
i < len(xs)is false. Sinceistarts at 1, which is at mostlen(xs), and goes up by one each time,i == len(xs)at exit. Thenxs[:i]is the whole list, sobestis its maximum.
The for x in xs[1:] version you saw earlier has the same invariant. The index is just hidden. "best is the largest element seen so far" means "best is the maximum of xs[:i]" for the unseen counter i.
Worked Example: Euclid's Algorithm
Euclid's loop is a different kind of case. Nothing gets accumulated. The variables change, but the quantity you care about stays the same.
Call the original inputs a0 and b0. The invariant is:
gcd(a, b) == gcd(a0, b0), with a >= 0 and b >= 0.
from math import gcd as reference_gcd
def gcd_checked(a, b):
assert a >= 0 and b >= 0 and (a, b) != (0, 0) # precondition
target = reference_gcd(a, b)
while b != 0:
assert reference_gcd(a, b) == target # invariant at test
a, b = b, a % b
assert reference_gcd(a, b) == target # invariant at exit
assert b == 0
return a
print(gcd_checked(48, 18)) # 6The checking code uses math.gcd only to test the invariant. The algorithm itself never calls it.
- Initialization. Before the first test,
a = a0andb = b0, so the invariant holds trivially. Both values are non-negative by the precondition. - Maintenance. When
b != 0, any number that divides bothaandbalso dividesa mod b = a - q*b. Going the other way, any number that dividesbanda mod balso dividesa. So the pairs(a, b)and(b, a mod b)have the same common divisors, and therefore the same greatest one. Also,a mod b >= 0. - Exit. When
b == 0,gcd(a, 0) = afora > 0. The valueacannot be 0 here. The precondition rules out(0, 0), and every step keeps the gcd equal to the original positive value. So the function returnsgcd(a0, b0).
A state table shows the invariant column staying fixed while the other values change:
| Test number | a | b | gcd(a, b) | Loop condition |
|---|---|---|---|---|
| 1 | 48 | 18 | 6 | true |
| 2 | 18 | 12 | 6 | true |
| 3 | 12 | 6 | 6 | true |
| 4 | 6 | 0 | 6 | false |
Finding an Invariant
Invariants rarely come out of nowhere. These are the common ways to find one:
- Generalize the postcondition. Replace a constant with a loop variable. "best is the max of
xs" becomes "best is the max ofxs[:i]". At exit, the loop variable reaches the constant. - Find the conserved quantity. If the loop transforms its inputs, ask what stays the same. For Euclid, that is the gcd.
- Trace and look for a pattern. Add a column to your state table for a candidate expression and check whether it stays true at every test.
| Algorithm | Postcondition | Invariant |
|---|---|---|
| Sum of a list | `total == sum(xs)` | `total == sum(xs[:i])` |
| Linear search | returns the first index of `target`, or -1 | `target not in items[:i]` |
| Find max | `best == max(xs)` | `best == max(xs[:i])` |
| Euclid's GCD | returns `gcd(a0, b0)` | `gcd(a, b) == gcd(a0, b0)` |
For linear search, the exit has two cases. If the loop returns early at index i, then items[i] == target and the invariant says no earlier index matched, so i is the first match. If the loop runs to the end, the invariant covers the whole list, so returning -1 is correct.
Common Errors
- Invariant too weak. "best is an element of
xs" is true at every test, but it doesn't give you the postcondition at exit. Check the exit obligation first. It quickly shows whether the invariant is useful. - Invariant false at initialization. Writing
best == max(xs[:i])withi = 0is a mistake, becausemax([])is undefined. The starting values must match the invariant. - Off-by-one in the range. Is it
xs[:i]orxs[:i+1]? That depends on whetherihas been incremented yet when control reaches the test. Decide where the test is, then state the invariant for that point. - Confusing the invariant with the loop condition.
i < len(xs)is the condition. It is false at exit, so it cannot be an invariant. - Checking maintenance without assuming the condition. The maintenance step may use the fact that the condition is true. For Euclid,
a mod bis only defined becauseb != 0. - Forgetting termination. A loop like
while True: passkeeps every invariant forever, but it never returns anything.
Exercise
Write a loop that computes total = sum(xs) for a list of numbers, using an index i. State the invariant and show that the exit obligation gives the postcondition.
Show answer
Start with total = 0 and i = 0, and loop while i < len(xs), doing total += xs[i] and then i += 1. The invariant is total == sum(xs[:i]). Initialization: sum([]) is 0. Maintenance: sum(xs[:i+1]) = sum(xs[:i]) + xs[i]. Exit: the condition is false and i only increases by 1 from 0, so i == len(xs), and therefore total == sum(xs).
Exercise
For find_max, someone proposes the invariant "best >= xs[0]". Is it true at every test? Is it a useful invariant? Explain.
Show answer
It is true at every test. It starts as equality, and best only ever increases. It is not useful, because at exit it does not imply that best is the maximum of xs. It fails the exit obligation, so it is too weak.
Exercise
In Euclid's algorithm, which step of the maintenance argument depends on the loop condition b != 0, and what goes wrong without it?
Show answer
Computing a mod b needs b != 0, because the remainder of division by zero is undefined. Python's a % 0 raises ZeroDivisionError. The divisor argument a mod b = a - q*b also needs a valid quotient q, which only exists when b is non-zero.