States and Invariants
3/22/19
1
State Space
• A state space is just a binary relation
on a set S (the set of “states”)
– (Meyer calls this a “state machine”)
• E.g. S = 3x3 arrangements of X, O,
blank
• a→b, where a, b ∈S, iff a move from
state a can result Xin state b X
X
O
3/22/19
→
X
O
X
→
O
O
2
Moving from state to state
• Many computational problems can be
described in terms of the states that
are reachable from a state after a
series of moves
X
• In tic-tac-toe, is O XX
reachable
from state
3/22/19
?
3
Invariant
• In tic-tac-toe, is
from state
O
X
X
X
reachable
?
No because tic-tac-toe preserves an
invariant property of states: #X=#O or
#X=#O+1
3/22/19
4
Invariant
Tic-tac-toe preserves an invariant property of
states: #X=#O or #X=#O+1
#X = #O = 0: Initial state
X always goes first
a→b: state b is a successor of state a
if #X=#O in a, then #X=#O+1 in b
if #X=#O+1 in a, then #X=#O in b
X
Therefore
is unreachable.
O
3/22/19
X
X
5
Floyd’s Invariant Principle
Preserved Invariant, P(state):
if P(q) and
q
r ,then
P(r)
• Conclusion: if P(start), then
P(r)
for all reachable states r,
including final state (if any)
3/22/19
6
Computing Factorials
n! = n∙(n-1)∙…∙2∙1
1.
2.
3.
4.
5.
Let b:=1, a:=n
If a=1 then return b
b := b∙a
a:=a-1
Go to step 2
• To prove Correctness (if it computes anything it
computes n!):
– Let state set S = N×N×N: the values of (a, b, n)
– (a, b, n) → (a-1, a∙b, n) in each iteration of loop steps 2-5
– Let P(a, b, n) ≡ “a! ∙ b = n!”
– Show
• P(n, 1, n)
• P(a, b, n) ⇒P(a-1, a∙b, n), because a! ∙ b = n ⇒ (a-1)! ∙ (a∙b) = n!
• So the loop preserves the invariant P(a, b, n)
– When & if a=1, since P(1, b, n) is true, b must be n!
3/22/19
7
1.
2.
3.
4.
5.
Computing Factorials
n!
=
n∙(n-1)∙…∙2∙1
Let b:=1, a:=n
If a=1 then return b
b := b∙a
a:=a-1
Go to step 2
• If the program computes anything it
computes n!
• But still must show Termination:
– a initially is n and decreases by 1 on
each iteration and therefore must
eventually reach 1
– PROVIDED n≥1 !!
3/22/19
8
FINIS
3/22/19
9