Professional Documents
Culture Documents
EppDM5e 05 05
EppDM5e 05 05
SEQUENCES, MATHEMATICAL
INDUCTION, AND RECURSION
3
Assertions
4
Assertions (1/1)
Consider an algorithm that is designed to produce a certain
final state from a certain initial state. Both the initial and
final states can be expressed as predicates involving the
input and output variables.
5
Example 5.5.1 – Algorithm Pre-Conditions and Post-Conditions (1/3)
6
Example 5.5.1 – Algorithm Pre-Conditions and Post-Conditions (2/3)
7
Example 5.5.1 – Algorithm Pre-Conditions and Post-Conditions (3/3)
8
Loop Invariants
9
Loop Invariants (1/5)
The method of loop invariants is used to prove correctness
of a loop with respect to certain pre- and post-conditions.
It is based on the principle of mathematical induction.
Suppose that an algorithm contains a while loop and that
entry to this loop is restricted by a condition G, called the
guard.
Suppose also that assertions describing the current states
of algorithm variables have been placed immediately
preceding and immediately the loop.
10
Loop Invariants (2/5)
The assertion just preceding the loop is called the pre-
condition for the loop and the one just following is called
the post-condition for the loop. The annotated loop has
the following appearance:
[Pre-condition for the loop]
while (G)
[Statements in the body of the loop.
None contain branching statements
that lead outside the loop.]
end while
[Post-condition for the loop]
11
Loop Invariants (3/5)
12
Loop Invariants (4/5)
Furthermore, if the predicate satisfies the following two
additional conditions, the loop will be correct with respect to
its pre- and post-conditions:
13
Loop Invariants (5/5)
The following theorem, called the loop invariant theorem,
formalizes these ideas. It was first developed by C. A. R.
Hoare in 1969.
14
Example 5.5.2 – Correctness of a Loop to Compute a Product (1/3)
15
Example 5.5.2 – Correctness of a Loop to Compute a Product (2/3)
16
Example 5.5.2 – Correctness of a Loop to Compute a Product (3/3)
Use the loop invariant theorem to prove that the while loop
is correct with respect to the given pre- and post-conditions.
17
Example 5.5.2 – Solution (1/5)
Ⅰ. Basis Property: [I(0) is true before the first iteration of
the loop.]
18
Example 5.5.2 – Solution (2/5) continued
productold = kx.
19
Example 5.5.2 – Solution (3/5) continued
iold = k,
inew = iold + 1 = k + 1.
20
Example 5.5.2 – Solution (4/5) continued
21
Example 5.5.2 – Solution (5/5) continued
22
Correctness of the Division
Algorithm
23
Correctness of the Division Algorithm (1/2)
24
Correctness of the Division Algorithm (2/2)
25
Correctness of the Euclidean
Theorem
26
Correctness of the Euclidean Theorem (1/2)
27
Correctness of the Euclidean Theorem (2/2)
28