140 likes | 328 Views
Loop correctness & Termination proff. Init; Invariant Loop. Pseudo-Code Notation. R is of the form: {r} T ; {inv : p } {bd : t } while B do S ; od {q}. require --- from init invariant inv variant var until exit loop body ensure --- end. Correctness Proof (1).
E N D
Loop correctness & Termination proff Init; Invariant Loop
Pseudo-Code Notation R is of the form: {r} T; {inv : p}{bd : t } whileBdo S; od {q} require --- frominit invariant inv variant var until exit loop body ensure --- end
Correctness Proof (1) • pis 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
Correctness Proof (2) • p implies t >= 0;that is p --> t >= 0 • t is decreased with each iteration;that is, {p /\ B /\ t = z}S{t < z}
Summation Problem Store in a variable ‘result’the sum of the elements in a given array. SUM = k := 0; result := 0;whilek != N do result := result + a[k]; k := k + 1; od
Pre, Post , Invariant Precondition: Postcondition: We choose the invariant :
The code array_sum (a: ARRAY[G]): G islocal i: INTEGERdo from i := a.lower invariantvalue: -- Result = limit: ia.upper + 1 andia.lowervarianta.upper + 1 – iuntili > a.upperloopresult := result + a @ i -- *** i := i + 1endensure -- result = end
Proof (1) (a) the invariant is true at the beginning of the first loop iteration; k == 0 result == 0 So the invariant trivially holds.
Proof (2) (b) the invariant is maintained by one pass through the loop body;p /\ B implies p. B : k != N p /\ B :
Proof (2) contd. 1. while k != N do 2. result := result + a[k]; 3. k := k + 1; 4. od Afer 2: This is p[k := k + 1] After 3:
Proof (3) (c) the postcondition follows from the invariant and the exit condition; p /\ !B implies q : !B : k == N P /\ !B :
Proof (4) (d) the variant is always non-negative; We choose the variant to be N - k and we have p implies N - k >= 0.
Proof (5) (e) the variant decreases by at least one in every pass through the loop body. As we pass through the loop we have k := k + 1; thus, the variant decreases by 1 with every iteration.
Mystery Program input(x,y) z := 1;while y != 0 doif odd(y)then y := y -1; z := x*z;else x := x * x; y := y / 2; output(z);