Computer Science · Book 3 · Bachelor Year 1

University Computer Science — Year 1

University Computer Science — Year 1 · Bachelor Year 1

12Program Correctness

A well-known book on programming presented a binary search, proved it correct, and tested it. The code was copied into the standard library of a major programming language, where it ran for about nine years before it failed: on an array of 2302^{30} elements or more, the line mid = (low + high) / 2 overflowed, and the search read outside the array. The proof had assumed integers without limits; the machine had 32-bit ones. Proofs of programs are worth their assumptions, and this chapter teaches how to state them: a specification says what a program must do, a loop invariant says why a loop does it, a variant says why it stops, and tests derived from the specification check the code against it on the cases a proof might have missed.

You already know

An assertion states a condition the program expects to hold at a point, and stops the program when it does not (Chapter 7). A variant is a quantity in a well-founded set that decreases at every iteration (Chapter 11). Binary search finds a value in a sorted array by halving the part still to search.

12.1 Specifications

Definition 12.1 (Precondition, postcondition, specification)

A precondition is a condition on the inputs, and on the state, that a caller must ensure before calling a function. A postcondition is a condition relating the result and the final state to the inputs, which the function guarantees when it returns. The pair is the function’s specification: a contract, in which the function owes nothing to a caller who broke the precondition.

def divide(a, b):
    """Precondition: a >= 0 and b > 0.
    Postcondition: returns (q, r) with a == q * b + r and 0 <= r < b."""
    assert a >= 0 and b > 0, "precondition"
    q, r = 0, a
    while r >= b:
        assert a == q * b + r and r >= 0, "invariant"  # holds at each test
        q, r = q + 1, r - b  # the variant r decreases by b > 0
    assert a == q * b + r and 0 <= r < b, "postcondition"
    return q, r
Listing 12.1. Integer division by repeated subtraction, with its contract checked code/bachelor-1/12-program-correctness/listings/division.py

The docstring states the specification in words; the assertions check it while the program runs. The postcondition a=qb+ra = qb + r and 0≤r<b0 \leq r < b determines qq and rr completely: it is a definition of integer division, while the loop is one way to compute it.

$ python division.py
(3, 2) (0, 0) (0, 4)
still running after 1000 steps: q=1000, r=17
AssertionError: precondition
Output 12.1. Three divisions; the loop without its precondition, stopped by a step cap; and the precondition refusing b=0b = 0.

12.2 Partial and total correctness

Definition 12.2 (Partial correctness, total correctness)

A program is partially correct with respect to a specification if every execution that starts in a state satisfying the precondition and terminates ends in a state satisfying the postcondition. It is totally correct if, moreover, every such execution terminates.

Partial correctness says nothing about the runs that never end: a loop while True: pass is partially correct for every specification. The division loop, run without its precondition, illustrates the difference: with b=0b = 0, r≥br \geq b stays true for ever, and the loop never ends; but whenever it does end, its result satisfies the postcondition, so it is partially correct even then. Total correctness is partial correctness plus termination, proved separately, by a variant: here rr, which decreases by b>0b > 0 at each iteration, and only because of the precondition.

Three kinds of runs from a state satisfying the precondition. Partial correctness forbids a run that stops in a state violating the postcondition; total correctness also forbids a run that never stops.
Three kinds of runs from a state satisfying the precondition. Partial correctness forbids a run that stops in a state violating the postcondition; total correctness also forbids a run that never stops.

12.3 Loop invariants

Definition 12.3 (Loop invariant)

A loop invariant is a condition on the variables of a loop that holds before the first test of the loop condition and is preserved by each iteration: if it holds and the loop condition is true before an iteration, it holds after it. It therefore holds at every test, and in particular when the loop exits.

Method 12.4 (Finding and using an invariant)

  1. Start from the postcondition, and weaken it into a condition that holds part of the way: drop a conjunct that the loop condition will supply at the exit (for division, keep a=qb+r∧r≥0a = qb + r \wedge r \geq 0 and drop r<br < b, which is the negation of r >= b), or replace a constant by a variable (for the maximum of xsxs, “mm is the maximum of xs[0:i]xs[0{:}i]” with ii in place of len(xs)\text{len}(xs)).
  2. Initialisation: prove that the invariant holds after the code before the loop.
  3. Preservation: assuming the invariant and the loop condition, prove the invariant after one iteration.
  4. Conclusion: prove that the invariant and the negation of the loop condition imply the postcondition.
  5. Termination: find a variant, and prove that it decreases at every iteration.
def maximum(xs):
    """Precondition: xs is not empty. Postcondition: returns m in xs, m >= every x."""
    m, i = xs[0], 1
    while i < len(xs):
        # invariant: m is the maximum of xs[0:i], and 1 <= i <= len(xs)
        assert m in xs[:i] and all(m >= x for x in xs[:i]) and 1 <= i <= len(xs)
        if xs[i] > m:
            m = xs[i]
        i += 1  # variant: len(xs) - i
    return m  # i == len(xs): m is the maximum of xs[0:len(xs)], all of xs
Listing 12.2. The maximum, with its invariant as an assertion code/bachelor-1/12-program-correctness/listings/maximum.py
$ python maximum.py
9 -5 3
Output 12.2. Three maxima, every invariant check passed.

The assertion turns the invariant into a check that runs at every iteration, which costs time (here it makes the loop quadratic) and is for development and tests only. The proof itself is Exercise 12.8. For the division, the obligations are short. Initialisation: q=0q = 0 and r=ar = a give a=0⋅b+aa = 0 \cdot b + a and r=a≥0r = a \geq 0. Preservation: if a=qb+ra = qb + r and r≥br \geq b, then a=(q+1)b+(r−b)a = (q + 1)b + (r - b) and r−b≥0r - b \geq 0. Conclusion: with r<br < b at the exit, the postcondition holds. Termination: rr is a natural number that decreases by b≥1b \geq 1.

12.4 Proofs for array algorithms

Partition

Partitioning around a pivot rearranges a slice so that the elements smaller than the pivot come first, then the pivot, then the others; quicksort is built on it in Chapter 19. Lomuto’s version scans the slice once, with two indices.

def partition(a, lo, hi, trace=False):
    """Precondition: lo < hi. Rearranges a[lo:hi] and returns k with
    a[lo:k] < p, a[k] == p, a[k+1:hi] >= p, where p is the pivot a[hi - 1]."""
    p = a[hi - 1]
    k = lo
    for j in range(lo, hi - 1):
        # invariant: a[lo:k] < p and a[k:j] >= p; a[j:hi-1] not yet seen
        if trace:
            print(f"j={j} k={k} {a[lo:k]} | {a[k:j]} | {a[j:hi - 1]} pivot {p}")
        if a[j] < p:
            a[k], a[j] = a[j], a[k]
            k += 1
    a[k], a[hi - 1] = a[hi - 1], a[k]  # the pivot between the two regions
    return k
Listing 12.3. Lomuto’s partition code/bachelor-1/12-program-correctness/listings/partition.py
$ python partition.py
j=0 k=0 [] | [] | [7, 2, 9, 4, 1, 8] pivot 5
j=1 k=0 [] | [7] | [2, 9, 4, 1, 8] pivot 5
j=2 k=1 [2] | [7] | [9, 4, 1, 8] pivot 5
j=3 k=1 [2] | [7, 9] | [4, 1, 8] pivot 5
j=4 k=2 [2, 4] | [9, 7] | [1, 8] pivot 5
j=5 k=3 [2, 4, 1] | [7, 9] | [8] pivot 5
result [2, 4, 1, 5, 9, 8, 7] pivot at 3
Output 12.3. The three regions before each step: smaller, not smaller, not yet seen.
The invariant of Lomuto’s partition: a[lo:k] < p and a[k:j] ≥ p, the rest unseen. A step looks at a[j] and extends one of the two regions; when j reaches hi - 1, the pivot is swapped into place k, between them.
The invariant of Lomuto’s partition: a[lo:k]<pa[lo{:}k] < p and a[k:j]≥pa[k{:}j] \geq p, the rest unseen. A step looks at a[j]a[j] and extends one of the two regions; when jj reaches hi−1hi - 1, the pivot is swapped into place kk, between them.

Proposition 12.5 (Lomuto’s partition is correct)

If lo<hilo < hi, partition(a, lo, hi) terminates, permutes a[lo:hi]a[lo{:}hi], and returns kk with a[lo:k]<a[k]a[lo{:}k] < a[k] and a[k+1:hi]≥a[k]a[k + 1{:}hi] \geq a[k], where a[k]a[k] is the original a[hi−1]a[hi - 1].

Proof. The loop runs jj from lolo to hi−2hi - 2, so it terminates, and the only changes to aa are swaps: a permutation. Invariant: a[lo:k]<pa[lo{:}k] < p and a[k:j]≥pa[k{:}j] \geq p. At the start, k=j=lok = j = lo, both regions are empty. If a[j]≥pa[j] \geq p, only jj moves: the second region gains a[j]a[j]. If a[j]<pa[j] < p, swapping a[k]a[k] and a[j]a[j] puts a[j]a[j] at the end of the first region and moves the first element of the second region (if any) to its end; then kk and jj move. At the exit, j=hi−1j = hi - 1: the slice is <p< p on [lo,k)[lo, k), ≥p\geq p on [k,hi−1)[k, hi - 1), and pp at hi−1hi - 1. The final swap puts pp at kk and the element a[k]≥pa[k] \geq p (if k<hi−1k < hi - 1) at hi−1hi - 1, inside the second region. ∎

Binary search on a half-open interval

The half-open interval [lo,hi)[lo, hi), the integers ii with lo≤i<hilo \leq i < hi, is the convenient way to describe a slice: its length is hi−lohi - lo, it is empty when lo=hilo = hi, and [lo,mid)[lo, mid) and [mid,hi)[mid, hi) split it without overlap. Binary search keeps such an interval of candidates.

def leftmost(a, x):
    """Precondition: a sorted. Returns the least i with a[i] >= x (len(a) if none):
    the position of the first x if x is present, where to insert it otherwise."""
    lo, hi = 0, len(a)
    while lo < hi:
        # invariant: a[:lo] < x <= a[hi:], and 0 <= lo <= hi <= len(a)
        mid = lo + (hi - lo) // 2  # lo <= mid < hi
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo  # lo == hi: a[:lo] < x <= a[lo:]
Listing 12.4. The leftmost position of xx, on [lo,hi)[lo, hi) code/bachelor-1/12-program-correctness/listings/bsearch.py
$ python bsearch.py
x= 3: leftmost 1, found
x= 2: leftmost 0, found
x= 9: leftmost 5, found
x= 5: leftmost 4, absent
x= 1: leftmost 0, absent
x=10: leftmost 6, absent
empty list: 0
Output 12.4. Present, with duplicates, at both ends, absent inside and outside, and the empty list.

Proposition 12.6 (Binary search is correct)

If aa is sorted, leftmost(a, x) terminates and returns the least ii with a[i]≥xa[i] \geq x, or len(a)\text{len}(a) if there is none.

Proof. Invariant: 0≤lo≤hi≤n0 \leq lo \leq hi \leq n, every element of a[:lo]a[{:}lo] is <x< x, and every element of a[hi:]a[hi{:}] is ≥x\geq x. Initially lo=0lo = 0 and hi=nhi = n, and both slices are empty. In an iteration lo<hilo < hi, so lo≤mid<hilo \leq mid < hi: midmid is a valid index, and the interval shrinks whichever branch runs. If a[mid]<xa[mid] < x, then, aa being sorted, all of a[:mid+1]a[{:}mid + 1] is <x< x, and lo=mid+1lo = mid + 1 keeps the invariant; otherwise all of a[mid:]a[mid{:}] is ≥x\geq x, and hi=midhi = mid keeps it. Variant: hi−lohi - lo, which decreases since mid+1>lomid + 1 > lo and mid<himid < hi. At the exit lo=hilo = hi: everything before lolo is <x< x and everything from lolo on is ≥x\geq x, so lolo is the least index with a[lo]≥xa[lo] \geq x, or nn. ∎

The invariant of binary search on [lo, hi): everything left of lo is smaller than x, everything from hi on is at least x, and the answer lies in [lo, hi]. Each step moves one end past mid.
The invariant of binary search on [lo,hi)[lo, hi): everything left of lolo is smaller than xx, everything from hihi on is at least xx, and the answer lies in [lo,hi][lo, hi]. Each step moves one end past midmid.

At most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 iterations run (Exercise 12.9). The midpoint is written lo+(hi−lo)/2lo + (hi - lo)/2 rather than (lo+hi)/2(lo + hi)/2: in Python both are correct, but in C the sum of two large int indices overflows (Chapter 2), which is exactly the failure of the opening story. The difference between the two versions is invisible to the proof unless the proof states that the variables are mathematical integers.

The three-colour flag

A list holds only the values 0, 1 and 2 (three colours); sort it in one pass, with swaps only. This is the three-colour flag problem, also called the Dutch national flag problem. Its invariant has four regions.

def flag(a):
    """Rearranges a so that all 0s come first, then 1s, then 2s; returns the swaps."""
    low, mid, high = 0, 0, len(a)
    swaps = 0
    while mid < high:
        # invariant: a[:low] == 0, a[low:mid] == 1, a[mid:high] unknown, a[high:] == 2
        if a[mid] == 0:
            a[low], a[mid] = a[mid], a[low]
            low, mid, swaps = low + 1, mid + 1, swaps + 1
        elif a[mid] == 1:
            mid += 1
        else:
            high -= 1
            a[mid], a[high] = a[high], a[mid]
            swaps += 1
    return swaps  # mid == high: the unknown region is empty
Listing 12.5. The three-colour flag in one pass code/bachelor-1/12-program-correctness/listings/flag.py
$ python flag.py
[0, 0, 0, 1, 1, 1, 2, 2, 2] 6 swaps
Output 12.5. Nine values sorted, with six swaps.
The four regions of the three-colour flag and the three cases of a step. Each step shrinks the unknown region by one, so high - mid is a variant; when it is empty, the list is sorted.
The four regions of the three-colour flag and the three cases of a step. Each step shrinks the unknown region by one, so high−midhigh - mid is a variant; when it is empty, the list is sorted.

In the case 2, mid does not advance: the value swapped in from high has not been examined yet. In the case 0, it may advance, because the value swapped out from low came from the region of 1s (or is the same element, when low=midlow = mid).

12.5 Testing against the specification

A proof covers every input but rests on assumptions and can contain errors; tests run the real code on the real machine but cover only the inputs they try. The specification connects them: it says what any correct output is, so it can judge outputs automatically.

Definition 12.7 (Test oracle, property-based test)

A test oracle is a procedure that decides whether an output is correct for an input: a check of the postcondition, or a comparison with a simpler program known to be correct (a brute-force or library version). A property-based test states a property that must hold for all inputs of a kind, generates many inputs at random, checks the property on each, and on a failure reports a smallest failing input it can find.

sorted_lists = st.lists(st.integers(-20, 20), max_size=40).map(sorted)


@given(sorted_lists, st.integers(-25, 25))
def test_leftmost_rightmost(a, x):
    assert leftmost(a, x) == bisect.bisect_left(a, x)
    assert rightmost(a, x) == bisect.bisect_right(a, x)
    i = leftmost(a, x)
    assert all(y < x for y in a[:i]) and all(y >= x for y in a[i:])  # the postcondition
Listing 12.6. Two oracles for binary search: the library and the postcondition code/bachelor-1/12-program-correctness/tests/test_bsearch.py

The library hypothesis generates the sorted lists and the values; the standard module bisect serves as the first oracle, and the postcondition, checked element by element, as the second. A test is only as good as its inputs: these lists hold small values, so that duplicates and absent values are frequent, which is where binary searches fail. No test, however many inputs it tries, would have found the overflow of the opening story on a machine with too little memory for an array of 2302^{30} elements: tests can show the presence of errors, and proofs their absence under stated assumptions.

Safe use

An assertion that checks an invariant can be expensive and can be disabled (Chapter 7); it must never have a side effect the program relies on. Inputs from users or files are checked by code that reports an error, not by assertions: a violated precondition at a public boundary is the caller’s error, and the program must say so.

12.6 Exercises

Exercise 12.1 ★

def f(a, b): return a - a % b is called with integers. Which of these specifications does it meet? (a) pre a≥0,b>0a \geq 0, b > 0; post bb divides the result. (b) pre a≥0,b>0a \geq 0, b > 0; post a−b<f(a,b)≤aa - b < f(a, b) \leq a. (c) pre b≠0b \neq 0; post the result is at most aa. (d) pre b>0b > 0; post the result is a multiple of bb, at most aa, and the largest such.

Solution

Solution of Exercise 12.1.

In Python, for b>0b > 0 the remainder a % b lies in [0,b)[0, b), so a−(a mod b)a - (a \bmod b) is the largest multiple of bb that is at most aa. (a) Met. (b) Met, since 0≤a mod b<b0 \leq a \bmod b < b. (c) Not met: for b<0b < 0 the remainder lies in (b,0](b, 0], and f(5, -3) returns 6, above aa. (d) Met, for negative aa too: Python’s remainder takes the sign of bb.

Exercise 12.2 ★

Give the values of ii and mm at each test of the loop of maximum([3, 9, 2, 9, 4]), and check the invariant at each.

Solution

Solution of Exercise 12.2.

At the five tests, (i,m)(i, m) is (1,3)(1, 3), (2,9)(2, 9), (3,9)(3, 9), (4,9)(4, 9) and (5,9)(5, 9), and the loop exits at the last. Each time mm is the maximum of xs[0:i]xs[0{:}i]: of [3][3], [3,9][3, 9], [3,9,2][3, 9, 2], [3,9,2,9][3, 9, 2, 9] and the whole list.

Exercise 12.3 ★

Does each loop terminate for every natural number nn? Give a variant or a run that does not stop. (a) while n != 0: n = n - 2. (b) while n > 1: n = n // 2. (c) while n > 0: n = n - 1 if n % 2 else n + 1. (d) while n % 7 != 0: n = n + 3.

Solution

Solution of Exercise 12.3.

(a) Stops for even nn, with variant nn; for odd nn it passes 1, then −1,−3,…-1, -3, \dots and never stops. (b) Stops: nn is a variant, halved while n>1n > 1. (c) Stops only for n=0n = 0 (no iteration) and n=1n = 1; from n=2n = 2 the values are 3,2,3,2,…3, 2, 3, 2, \dots, and from any n≥2n \geq 2 the loop alternates between an even and an odd number for ever. (d) Stops: since 3 and 7 are coprime, n,n+3,…,n+18n, n + 3, \dots, n + 18 meet every remainder modulo 7; the variant is the least k≥0k \geq 0 with 7∣n+3k7 \mid n + 3k, at most 6, which drops by one at each iteration.

Exercise 12.4 ★

Predict what the program prints.

from bsearch import leftmost

print(leftmost([1, 1, 1], 1), leftmost([1, 1, 1], 2), leftmost([1, 1, 1], 0))
print(leftmost([1, 2, 2, 2, 3], 2), leftmost([1, 2, 2, 2, 3], 3), leftmost([4], 4))
Listing 12.7. Duplicates and the leftmost position code/bachelor-1/12-program-correctness/listings/exo_dups.py
Solution

Solution of Exercise 12.4.

0 3 0
1 4 0
Output 12.9. The leftmost positions. Some lines are left out.

In [1,1,1][1, 1, 1]: the first 1 is at 0; 2 would go at the end (3); 0 at the start (0). In [1,2,2,2,3][1, 2, 2, 2, 3]: the first 2 is at 1, the 3 at 4; in [4][4], 4 is at 0.

Exercise 12.5 ★★

This search uses a closed interval [lo,hi][lo, hi] but updates it as a half-open one. Find the inputs on which it never stops, explain why with the variant, and correct it with its invariant.

def search(a, x, max_steps=20):
    lo, hi = 0, len(a) - 1
    steps = 0
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == x:
            return mid
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid  # should be mid - 1 on a closed interval
        steps += 1
        if steps == max_steps:
            return f"stuck: lo={lo} hi={hi} mid={mid} after {steps} steps"
    return -1
Listing 12.8. A search that can loop code/bachelor-1/12-program-correctness/listings/bsearch_bug.py
1 -1
stuck: lo=0 hi=0 mid=0 after 20 steps
Output 12.6. Two answers, then a step cap. Some lines are left out.
Solution

Solution of Exercise 12.5.

On a closed interval the variant is the number of candidates, hi−lo+1hi - lo + 1. When lo<hilo < hi, mid<himid < hi and hi = mid decreases it; but when lo=hi=midlo = hi = mid and a[mid]>xa[mid] > x, hi = mid changes nothing, and the loop repeats the same state. This happens whenever xx is absent and the search ends next to a larger element: in [2,5,8][2, 5, 8], for x=1x = 1 (lo=hi=0lo = hi = 0), and also for x=3x = 3 or x=6x = 6. The fix is hi = mid - 1, with the invariant “every element of a[:lo]a[{:}lo] is <x< x and every element of a[hi+1:]a[hi + 1{:}] is >x> x”: a[mid]>xa[mid] > x and the list is sorted, so a[mid:]a[mid{:}] is >x> x; and the variant hi−lo+1hi - lo + 1 now decreases in all three branches. The half-open version of Listing 12.4 avoids mixing the two conventions.

Exercise 12.6 ★★

A student writes the partition with a copy instead of a swap. Which part of the proof of Proposition 12.5 fails, and what happens to the list?

def partition_bug(a, lo, hi):
    p = a[hi - 1]
    k = lo
    for j in range(lo, hi - 1):
        if a[j] < p:
            a[k] = a[j]
            k += 1
    a[k], a[hi - 1] = a[hi - 1], a[k]
    return k
Listing 12.9. A partition with a copy code/bachelor-1/12-program-correctness/listings/exo_partition_bug.py
[2, 4, 1, 5, 1, 8, 4] pivot at 3
sorted: [1, 1, 2, 4, 4, 5, 8] instead of [1, 2, 4, 5, 7, 8, 9]
Output 12.7. The result. Some lines are left out.
Solution

Solution of Exercise 12.6.

Preservation fails. With a[k] = a[j] the element at kk, which belongs to the region ≥p\geq p, is overwritten and lost, and the small a[j]a[j] stays where it was, inside the region a[k:j]a[k{:}j], which is no longer ≥p\geq p. The result is not a permutation (7 and 9 are lost, 1 and 4 appear twice), and it is not even partitioned: 1 and 4 come after the pivot 5. The test of Proposition 12.5’s two conclusions catches both at once.

Exercise 12.7 ★★

Write rightmost(a, x), which returns the least ii with a[i]>xa[i] > x in a sorted list, on a half-open interval, with its invariant as a comment. Deduce the number of occurrences of xx, and test both against bisect.

Solution

Solution of Exercise 12.7.

def rightmost(a, x):
    """Precondition: a sorted. Returns the least i with a[i] > x (len(a) if none)."""
    lo, hi = 0, len(a)
    while lo < hi:
        # invariant: a[:lo] <= x < a[hi:], and 0 <= lo <= hi <= len(a)
        mid = lo + (hi - lo) // 2
        if a[mid] <= x:
            lo = mid + 1
        else:
            hi = mid
    return lo
One past the last occurrence code/bachelor-1/12-program-correctness/exercises/rightmost.py

The proof is that of Proposition 12.6, with ≤\leq in place of <<: if a[mid]≤xa[mid] \leq x, all of a[:mid+1]a[{:}mid + 1] is ≤x\leq x; otherwise all of a[mid:]a[mid{:}] is >x> x. The occurrences of xx are exactly a[leftmost:rightmost]a[\mathit{leftmost}{:}\mathit{rightmost}], so their number is the difference, as the output of Listing 12.4 showed for x=3x = 3. The test compares both functions with bisect_left and bisect_right on random sorted lists with many duplicates.

Exercise 12.8 ★★

Prove that maximum is totally correct, with the invariant of Listing 12.2 and the variant len(xs)−i\text{len}(xs) - i.

Solution

Solution of Exercise 12.8.

Let n=len(xs)≥1n = \text{len}(xs) \geq 1. Invariant: 1≤i≤n1 \leq i \leq n, m∈xs[0:i]m \in xs[0{:}i] and m≥xm \geq x for every xx of xs[0:i]xs[0{:}i]. Initialisation: i=1i = 1, m=xs[0]m = xs[0], the maximum of [xs[0]][xs[0]]. Preservation: with i<ni < n, if xs[i]>mxs[i] > m the new mm is xs[i]xs[i], larger than every element of xs[0:i]xs[0{:}i]; otherwise m≥xs[i]m \geq xs[i] already; either way mm is the maximum of xs[0:i+1]xs[0{:}i + 1], and i+1≤ni + 1 \leq n. Conclusion: at the exit i≥ni \geq n and i≤ni \leq n, so i=ni = n and mm is the maximum of the whole list. Termination: n−in - i is a natural number that decreases by one.

Exercise 12.9 ★★

Prove that binary search on n≥1n \geq 1 elements makes at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 iterations, and that the bound is reached.

Solution

Solution of Exercise 12.9.

Let L=hi−lo≥1L = hi - lo \geq 1 and mid=lo+⌊L/2⌋mid = lo + \lfloor L/2 \rfloor. After hi = mid the length is ⌊L/2⌋\lfloor L/2 \rfloor; after lo = mid + 1 it is L−⌊L/2⌋−1=⌈L/2⌉−1≤⌊L/2⌋L - \lfloor L/2 \rfloor - 1 = \lceil L/2 \rceil - 1 \leq \lfloor L/2 \rfloor. So after kk iterations the length is at most ⌊n/2k⌋\lfloor n/2^k \rfloor, which is 0 for k=⌊log⁡2n⌋+1k = \lfloor \log_2 n \rfloor + 1, since then 2k>n2^k > n: the loop has stopped. The bound is reached when xx is below every element: every step takes hi = mid, and the length goes n,⌊n/2⌋,⌊n/4⌋,…n, \lfloor n/2 \rfloor, \lfloor n/4 \rfloor, \dots, which stays positive for ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 values. The test checks the worst case for every n<300n < 300.

Exercise 12.10 ★★★

The flag of Listing 12.5 sorts in one pass, but not with the fewest swaps. Find a list on which it makes more swaps than necessary. Then write min_swaps(a), the least number of swaps that sort a list of 0, 1 and 2, and check it against a search over all orders for lists of up to six values.

Solution

Solution of Exercise 12.10.

On [2,2,0][2, 2, 0] the flag makes 3 swaps (two of them swap an element with itself), where one swap of the first and last elements sorts the list; on the list of Output 12.5, 6 swaps where 3 suffice.

def min_swaps(a):
    """c[i][j]: elements of value i lying in the region where value j belongs.
    A pair i <-> j of misplaced elements is fixed by one swap; what remains
    forms cycles of three elements, each fixed by two swaps."""
    bounds = [0, a.count(0), a.count(0) + a.count(1), len(a)]
    c = [[0] * 3 for _ in range(3)]
    for j in range(3):
        for x in a[bounds[j]:bounds[j + 1]]:
            c[x][j] += 1
    pairs = sum(min(c[i][j], c[j][i]) for i in range(3) for j in range(i + 1, 3))
    left = sum(c[i][j] for i in range(3) for j in range(3) if i != j) - 2 * pairs
    return pairs + 2 * (left // 3)
The fewest swaps code/bachelor-1/12-program-correctness/exercises/min_swaps.py

Count c[i][j]c[i][j], the elements of value ii in the region where jj belongs. A swap moves at most two elements to their place, and does so only for a pair i↔ji \leftrightarrow j with c[i][j]>0c[i][j] > 0 and c[j][i]>0c[j][i] > 0; take as many such swaps as possible. The misplaced elements left form cycles 0→1→2→00 \to 1 \to 2 \to 0 (or the reverse), in equal numbers tt in each of the three counts, and a cycle of three needs two swaps, each placing at most one element beyond the pairs. The minimum is pairs+2t\text{pairs} + 2t, with 3t3t the elements left. The test compares it with a breadth-first search over all orders reached by swaps, for every list of 0, 1 and 2 of length at most 6, and checks that the flag never does better.

Exercise 12.11 ★★★

Find what this function computes, state its specification, and prove it totally correct with an invariant relating acc, base and e to xx and nn. How many iterations does it make?

def mystery(x, n):
    """Precondition: n >= 0."""
    acc, base, e = 1, x, n
    while e > 0:
        if e % 2 == 1:
            acc = acc * base
        base = base * base
        e = e // 2
    return acc
Listing 12.10. A loop to understand code/bachelor-1/12-program-correctness/listings/exo_mystery.py
Solution

Solution of Exercise 12.11.

1594323 1024 1
Output 12.10. Three values. Some lines are left out.

It computes xnx^n: 313=1 594 3233^{13} = 1\,594\,323, 210=10242^{10} = 1024, 70=17^0 = 1. Specification: pre n≥0n \geq 0, post the result is xnx^n. Invariant: acc⋅basee=xn\mathit{acc} \cdot \mathit{base}^e = x^n and e≥0e \geq 0. Initially 1⋅xn1 \cdot x^n. If ee is odd, acc⋅base⋅(base2)(e−1)/2=acc⋅basee\mathit{acc} \cdot \mathit{base} \cdot (\mathit{base}^2)^{(e - 1)/2} = \mathit{acc} \cdot \mathit{base}^e; if ee is even, acc⋅(base2)e/2=acc⋅basee\mathit{acc} \cdot (\mathit{base}^2)^{e/2} = \mathit{acc} \cdot \mathit{base}^e. At the exit e=0e = 0 and acc=xn\mathit{acc} = x^n. Variant: ee, halved at each step. The number of iterations is the number of binary digits of nn, ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 for n≥1n \geq 1, and 0 for n=0n = 0: 4 for n=13n = 13. The test compares with x ** n.

Exercise 12.12 ★★★

A student proves that the loop s = 0; i = 0; while i < n: i = i + 1; s = s + i computes s=n(n+1)/2s = n(n + 1)/2 with the invariant “s=i(i+1)/2s = i(i + 1)/2 and i≤ni \leq n”, and proves the conclusion as follows: “at the exit i≤ni \leq n and i≥ni \geq n, so i=ni = n”. The same student proves that while i != n: i = i + 2 (from i=0i = 0) ends with i=ni = n, with the invariant “ii is even”. Which proof is right, which is wrong, and where exactly?

Solution

Solution of Exercise 12.12.

The first proof is right, for n≥0n \geq 0: s+i+1=(i+1)(i+2)/2s + i + 1 = (i + 1)(i + 2)/2 preserves the first part, i<ni < n before the step gives i+1≤ni + 1 \leq n after it, and the exit gives i=ni = n. The second is a correct proof of partial correctness only: at the exit i=ni = n by the loop condition alone, and the invariant “ii is even” plays no part. What is missing is termination, and it is false for odd nn (and negative nn), where ii jumps over nn for ever. The invariant should be “ii is even and i≤ni \leq n”, which needs the precondition “nn even and n≥0n \geq 0”; then n−in - i is a variant.

12.7 Problem: The square root that never lies

Problem 12.1

Weekend problem — The square root that never lies

The integer square root of a natural number nn is the rr with r2≤n<(r+1)2r^2 \leq n < (r + 1)^2. Two programs compute it: bisection on the half-open interval [0,n+1)[0, n + 1), and Newton’s method on integers, started at nn. Both are compared with the library’s math.isqrt on twelve values up to 264−12^{64} - 1, and by a property-based test on random 64-bit values.

def isqrt_bisect(n):
    lo, hi = 0, n + 1  # invariant: lo * lo <= n < hi * hi
    steps = 0
    while hi - lo > 1:  # variant: hi - lo
        mid = (lo + hi) // 2  # lo < mid < hi
        if mid * mid <= n:
            lo = mid
        else:
            hi = mid
        steps += 1
    return lo, steps


def isqrt_newton(n):
    if n == 0:
        return 0, 0
    r = n  # invariant: r >= the integer square root of n
    steps = 0
    while r * r > n:  # variant: r, which decreases strictly
        r = (r + n // r) // 2
        steps += 1
    return r, steps
Listing 12.11. Two integer square roots code/bachelor-1/12-program-correctness/listings/isqrt.py
$ python isqrt.py
                     n        root bisection ceil(log2(n+1)) Newton
                     0           0         0               0      0
                     1           1         1               1      0
                     2           1         2               2      1
                    15           3         4               4      3
                    16           4         4               5      3
                    17           4         4               5      3
                    99           9         6               7      5
               1000000        1000        20              20     12
            4294967295       65535        32              32     20
            4294967296       65536        32              33     19
   1000000000000000000  1000000000        60              60     34
  18446744073709551615  4294967295        64              64     37
Output 12.8. Equal roots, and the iterations of each method.

Part I — The specification.

  1. Show that for each n≥0n \geq 0 exactly one natural number rr satisfies r2≤n<(r+1)2r^2 \leq n < (r + 1)^2.
  2. Show that the specification can be checked with two multiplications, without computing any square root.
  3. Why is ⌊n⌋\lfloor \sqrt{n} \rfloor, computed in floating point, not a correct implementation for 64-bit nn? Give the order of magnitude of nn beyond which float cannot even represent every integer.
  4. Give the specification of isqrt_bisect and isqrt_newton as precondition and postcondition, counting the returned number of steps.
  5. Write a test oracle for the integer square root that uses only the specification.
  6. Why do the programs return the step counts with the result?

Part II — Bisection.

  1. Check that the invariant lo2≤n<hi2lo^2 \leq n < hi^2 holds initially.
  2. Show that it is preserved, and that lo<mid<hilo < mid < hi in every iteration.
  3. Show that hi−lohi - lo is a variant, and deduce termination.
  4. Prove the conclusion: at the exit, lolo satisfies the specification.
  5. Show that the number of iterations is at most ⌈log⁡2(n+1)⌉\lceil \log_2 (n + 1) \rceil, and compare with the table.
  6. In C with 64-bit unsigned integers, which expressions of isqrt_bisect can overflow for n=264−1n = 2^{64} - 1? How would you avoid it?

Part III — Newton’s method on integers.

  1. Let ss be the integer square root of n≥1n \geq 1. For an integer r≥1r \geq 1, show that ⌊(r+⌊n/r⌋)/2⌋=⌊(r+n/r)/2⌋\lfloor (r + \lfloor n/r \rfloor)/2 \rfloor = \lfloor (r + n/r)/2 \rfloor.
  2. Show that (r+n/r)/2≥n(r + n/r)/2 \geq \sqrt{n} for r>0r > 0, and deduce that the new rr is at least ss: the invariant r≥sr \geq s is preserved.
  3. Show that if r2>nr^2 > n, the new rr is strictly smaller than rr.
  4. Deduce that the loop terminates, and that at the exit r=sr = s.
  5. Why must the case n=0n = 0 be treated apart?
  6. Why does the loop test r2>nr^2 > n rather than r≠r \neq new rr?

Part IV — Tests and counts.

  1. Read the table: for which nn does bisection reach ⌈log⁡2(n+1)⌉\lceil \log_2 (n + 1) \rceil, and for which does it stay below?
  2. Newton’s method needs 37 iterations for 264−12^{64} - 1. Explain why the first iterations roughly halve rr, and why the last few are fast.
  3. Suggest a better starting value than nn and say what must be proved again.
  4. The property-based test draws nn at random below 2642^{64}. Why does it also check every n<2000n < 2000 separately?
  5. What would the test have caught if isqrt_newton returned rr with r2≥nr^2 \geq n rather than r2>nr^2 > n in its loop condition? Check by reasoning on n=16n = 16.
  6. State the named result of the problem, Newton’s integer square root is totally correct, with the measured iteration counts against bisection’s.
Solution

Solution of Problem 12.1.

1. Existence: {r∈N:r2≤n}\{r \in \mathbb{N} : r^2 \leq n\} contains 0 and is bounded by n+1n + 1; its largest element rr has (r+1)2>n(r + 1)^2 > n. Uniqueness: if r<r′r < r' both satisfied it, then r+1≤r′r + 1 \leq r' and (r+1)2≤r′2≤n(r + 1)^2 \leq r'^2 \leq n, a contradiction.

2. Compute r⋅rr \cdot r and (r+1)⋅(r+1)(r + 1) \cdot (r + 1) and compare them with nn.

3. A float has a 53-bit significand: above 253≈9×10152^{53} \approx 9 \times 10^{15} not every integer is representable, and nn is rounded before the root is taken. For n=264−1n = 2^{64} - 1, math.floor(math.sqrt(n)) gives 4 294 967 296, one too many.

4. Precondition: nn is an integer, n≥0n \geq 0. Postcondition: the result is (r,k)(r, k) with r2≤n<(r+1)2r^2 \leq n < (r + 1)^2 and kk the number of iterations made.

5. assert r * r <= n < (r + 1) * (r + 1), which needs neither program nor library.

6. To compare the methods in Part IV; the test bounds them as well.

7. 02=0≤n0^2 = 0 \leq n and n<(n+1)2n < (n + 1)^2.

8. In an iteration hi≥lo+2hi \geq lo + 2, so lo+1≤mid≤hi−1lo + 1 \leq mid \leq hi - 1. If mid2≤nmid^2 \leq n, lo = mid keeps lo2≤nlo^2 \leq n; otherwise n<mid2n < mid^2 and hi = mid keeps n<hi2n < hi^2.

9. hi−lohi - lo is a natural number (lo2≤n<hi2lo^2 \leq n < hi^2 gives lo<hilo < hi) and decreases strictly, since midmid lies strictly between lolo and hihi; the loop runs only while it exceeds 1.

10. At the exit lo<hi≤lo+1lo < hi \leq lo + 1, so hi=lo+1hi = lo + 1, and the invariant reads lo2≤n<(lo+1)2lo^2 \leq n < (lo + 1)^2.

11. A step leaves mid−lo=⌊L/2⌋mid - lo = \lfloor L/2 \rfloor or hi−mid=⌈L/2⌉hi - mid = \lceil L/2 \rceil, so after kk steps the length is at most ⌈(n+1)/2k⌉\lceil (n + 1)/2^k \rceil, which is 1 once 2k≥n+12^k \geq n + 1: at most ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil steps. The table reaches the bound except for 16, 17, 99 and 2322^{32}, one below.

12. n+1n + 1 is 0 for n=264−1n = 2^{64} - 1; lo+hilo + hi can exceed 2642^{64}; and mid⋅midmid \cdot mid overflows once mid≥232mid \geq 2^{32}. Start with hi=232hi = 2^{32} (the root of a 64-bit number is below it, so n<hi2n < hi^2 holds), compute mid=lo+(hi−lo)/2mid = lo + (hi - lo)/2, and test mid≤n/midmid \leq n / mid (for mid≥1mid \geq 1) instead of mid2≤nmid^2 \leq n.

13. Write n/r=q+fn/r = q + f with q=⌊n/r⌋q = \lfloor n/r \rfloor and 0≤f<10 \leq f < 1, and m=r+qm = r + q. If mm is even, ⌊(m+f)/2⌋=m/2\lfloor (m + f)/2 \rfloor = m/2; if mm is odd, (m+f)/2=(m−1)/2+(1+f)/2(m + f)/2 = (m - 1)/2 + (1 + f)/2 with (1+f)/2<1(1 + f)/2 < 1, so the floor is (m−1)/2(m - 1)/2. Either way it is ⌊m/2⌋\lfloor m/2 \rfloor.

14. (r+n/r)/2−n=(r−n/r)2/2≥0(r + n/r)/2 - \sqrt{n} = (\sqrt{r} - \sqrt{n/r})^2/2 \geq 0. Taking floors, the new rr is at least ⌊n⌋=s\lfloor \sqrt{n} \rfloor = s. Initially r=n≥sr = n \geq s, since s≤s2≤ns \leq s^2 \leq n for s≥1s \geq 1.

15. r2>nr^2 > n gives n/r<rn/r < r, so (r+n/r)/2<r(r + n/r)/2 < r, and its floor is below rr.

16. rr is a natural number that decreases strictly at each iteration: the loop stops. At the exit r2≤nr^2 \leq n, so r≤sr \leq s, the largest number whose square is at most nn; with the invariant r≥sr \geq s, r=sr = s.

17. The first step computes n // r with r=n=0r = n = 0: a division by zero.

18. The values can oscillate between ss and s+1s + 1: for n=15n = 15, r=4r = 4 gives 3, and r=3r = 3 gives 4, and so on. The test r2>nr^2 > n stops at 3.

19. The bound is reached for 0, 1, 2, 15, 10610^6, 232−12^{32} - 1, 101810^{18} and 264−12^{64} - 1; bisection stays one below for 16, 17, 99 and 2322^{32}, where the intervals happen to shrink a little faster than half.

20. While rr is far above n\sqrt{n}, n/rn/r is small beside rr, and the new rr is about r/2r/2: from 2642^{64} to near 2322^{32} takes about 32 steps. Near n\sqrt{n} the error is roughly squared at each step (it becomes about e2/(2r)e^2/(2r)), so a handful of steps finish: 32+5=3732 + 5 = 37.

21. Start at 2⌈b/2⌉2^{\lceil b/2 \rceil} with bb the number of binary digits of nn: since n<2bn < 2^b, n<2b/2\sqrt{n} < 2^{b/2}, so it is at least ss. Only the initialisation of the invariant must be proved again; preservation, conclusion and termination do not depend on the start.

22. Random 64-bit values almost never land on perfect squares, their neighbours or tiny values, where the boundary errors live; the exhaustive check below 2000 covers them all.

23. For n=16n = 16: rr goes 16,8,5,416, 8, 5, 4, then 4⋅4≥164 \cdot 4 \geq 16 still holds and rr stays 4 for ever. The variant fails when r2=nr^2 = n: the new rr equals rr. The test would never finish: the exhaustive loop hangs at n=1n = 1, where r=1r = 1 stays 1.

24. Newton’s integer square root is totally correct: for every n≥0n \geq 0, isqrt_newton(n) terminates and returns the rr with r2≤n<(r+1)2r^2 \leq n < (r + 1)^2 (questions 13–16). On the table it needs 0, 0, 1, 3, 3, 3, 5, 12, 20, 19, 34 and 37 iterations, against bisection’s 0, 1, 2, 4, 4, 4, 6, 20, 32, 32, 60 and 64, which never exceed ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil.

Terms defined in this chapter

See all 1050 terms in the glossary