200 likes | 211 Views
This text discusses loop invariants and general notation in the correctness and termination proof of loops. It also presents an example problem and demonstrates the development of a program with its correctness proof.
E N D
General Notation require --- frominit invariant inv variant var until exit loop body ensure --- end R is of the form: {r} T; {inv : p}{bd : t } whileBdo S; od {q}
Correctness Proof • p is initially established;that is {r}T{p} holds. • p is a loop invariant;that is, {p /\ B}S{p} holds. • Upon loop termination q is true;that is, p /\ !B --> q • p implies t >= 0;that is p --> t >= 0 • t is decreased with each iteration; that is, {p /\ B /\ t = z}S{t < z} Correctness Termination
… MINSUM Problem 0 1 2 3 4 N We’re looking for a section a[i:j] s.t. the sum of the elements in this subsection is minimal over all possible subsections. a:
MINSUM - Examples 0 1 2 3 4 a: 5 -3 2 -4 1 minimum-sum section is a[1:3] = (-3,2,-4). The sum is -5. 0 1 2 3 4 a: 5 2 5 4 2 The two minimum-sum sections are a[1:1] and a[4:4]. The sum is 2.
The Problem {N > 0} MINSUM {q}
We introduce the following notation The sum of the minimum-sum section of a[0:k-1] Then we have
Pre-condition We try finding the invariant p by replacing the constant N in the postcondition q by a variable k and by putting the appropriate bounds on k:
We now attempt to satisfy conditions 1-5 choosing B, S, and t in an appropriate way. {r} T; {inv : p}{bd : t } whileBdo S; od {q}
1. p is initially established To establish {N>0}T{p} we choose as initialization: T :k := 1; sum := a[0];
3. Upon loop termination q is true To establish p /\ !B --> q we choose B to beB : k != N
4. p implies t >= 0 Because p --> N - k >= 0 we chooset : N - k as the bound function. (variant)
5. t is decreased with each iteration To decrease the bound function with each iteration we put k := k + 1;at the end of each loop.
2. p is a loop invariant that is, {p /\ B}S{p} holds.
{N > 0}k := 1; sum := a[0];{inv:p}{t : N-k}whilek != Ndo {p /\ (k != N)} S’; {p[k := k + 1]}k := k + 1; {p}od{p /\ (k == N)}{q} S
Finding S’ We compare the precondition and postcondition of S’. Using the abbreviation
Finding S’ (cont.) It is easy to check that the assignment Transforms the precondition into the desired postcondition.
Computing tk+1 Efficient Computation: We introduce a new variable x We express tk+1 with the help of tk
S’ S’ :x := min(x + a[k], a[k]);sum := min(sum,x);
MINSUM MINSUM : k : = 1; sum := a[0]; x := 0;while k != N do x := min(x + a[k], a[k]); sum := min(sum,x); k := k + 1;od We have developed the program together with its correctness proof.