States and invariants

Download Report

Transcript States and invariants

States and Invariants
7/12/2016
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 in state b
X
X
O
7/12/2016
→
X
O
X
→
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
X reachable
• In tic-tac-toe, is
O
from state
7/12/2016
X
?
3
Invariant
X
• In tic-tac-toe, is
reachable
X
O
from state
X
?
No because tic-tac-toe preserves an invariant
property of states: #X=#O or #X=#O+1
7/12/2016
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.
X
O
7/12/2016
X
5
Floyd’s Invariant Principle
Preserved Invariant, P(state):
if P(q) and
q
,then
P(r)
r
• Conclusion: if P(start), then P(r)
for all reachable states r,
including final state (if any)
7/12/2016
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!
7/12/2016
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 !!
7/12/2016
8
FINIS
7/12/2016
9