Sunday, November 9, 2008

Proving the correctness of iteration and recursion

Basically, iteration and recursion are both loops. The difference is that recursion continues to call the function itself until it gets to a base case, while iteration has variables which change after each iteration.
Considering proofs of the correctness of iteration or recursion , I find out that it is easier to prove recursion by using complete induction. I assume P(1) and P(2) and ... and P(n-1) is true where n is a parameter about the function. Then I check that when the function calls itself, the parameter about the just called function is within the domain of (1, n-1) so that by assumption, the just called function returns the correct result.
As far as iteration is concerned, I need to have loop invariants which are true after each iteration. Loop invariants depends on the i-th iteration (i = 0, 1, 2,...), so the expression for loop invariants has parameter i. I need to prove the expression holds for every i using simple induction. Also, it's necessary to prove the iteration terminates. To prove that, I need to find an expression composed of loop invariants and prove it is a decreasing sequence so that the iteration terminates at last.

No comments: