COL100 Lecture 11
COL100 Lecture 11
Correctness of
Iterative Programs
Proving loop correctness
def function(arguments):
# INPUT specification on arguments
# OUTPUT specification
# Identify a property that holds BEFORE and AFTER the loop body
# This is called a LOOP INVARIANT
# ESTABLISH INVARIANT holds just as you enter loop
# i.e., INPUT spec and INITIALISATION IMPLIES INVARIANT
# execute the statements in the LOOP BODY
# CHECK INVARIANT holds after executing LOOP BODY
def fact(n):
# INPUT n >= 0
# OUTPUT ans == n!
# INVARIANT variable ans ==(i-1)!
ans = 1
i = 1 # i-1 == 0 and ans == 1 == 0!
while i <= n: # — TERMINATION: n-i+1 decreases to 0
# ASSERT INVARIANT ans == (i-1)!
ans = ans * i
# — ans now has value i!
i = i+1
# CHECK INVARIANT ans == (i-1)!
# — EXIT CONDITION: i > n, i.e. i == n+1
# ans == (i-1)! and i == n+1 IMPLIES ans == n!
return ans
Iterative Fibonacci program
def fib(n):
# INPUT n >= 0
# OUTPUT ans == nth fib number
ans = 1
if (n==0) or (n==1):
return ans
else:
prev = 1
i = 2
“There is a set”
• How can one prove this claim?
• By producing a set
• What is the easiest set to produce?
• The empty set 0 = { }
• What is the characteristic function of 0?
• f(x) which returns False for every input x
• Exercise: Define this function for integers.
Singleton Set
“There is a set with exactly one element”
• The singleton set 1 = { • }
• Many such singletons, but all are “isomorphic”
• Characterised by: x in 1 /\ y in 1 implies x = y
Cartesian Product
Cartesian Product
• Note: A x B =/= B x A
• but A x B ~ B x A (exists bijection between the sets)
• map (a,b) in A x B |—> (b,a) in B x A and vice versa
• (A x B) x C ~ A x (B x C) ~ A x B x C (but they are all different)
• map ((a,b),c) in (A x B) x C to (a,(b,c)) in A x (B x C)
• Exercise: Prove these are bijections
• A x 0 = 0 and 0 x B = 0 (Prove this)
• A x 1 ~ A and 1 x B ~ B (Prove this)
Relations
Relation R between two sets A and B is any subset of A x B.
Generalises to k-ary relations: subsets of A1 x … x Ak
Relational Inverse:
Given R a relation between A and B,
R— = { (b,a) | (a,b) in R } is a relation between B and A
(Partial) Function:
Relation R between two sets A and B is a (partial) function if
for each a in A, there is (at most) one b in B such that (a,b) in R.
We write f: A —> B if f is a functional relation.
We write f(a) = b if (a,b) is in a functional relation f: A —> B
A + 0 = A and 0 + B = B
Defined by Induction
• 0 is in N (Base case)
• If n is in N then successor of n (i.e., n+1) is in N (Induction case)
How does one “count” infinite sets?
The cardinality | A | of A ≤ the cardinality | B | of B if there is a total 1-1 function from A to B
Fact: N is denumerable.
Proof: IdN is a bijection from N to N
Defined by Induction
• [ ] is in N list (Base case)
• If x is in N and l is in N list then the list with first element x and rest of the list
as l is also in N list (Induction case)