Loop Invariants CSC 171 FALL 2001 LECTURE 6
History: Herman Hollerith Herman is said to have been a bright and able child at school, but had an inability to learn spelling easily. His determined teacher made his life miserable to the extent that he used to avoid school whenever possible and run away when his teacher showed renewed effort to improve his spelling.
History: Herman Tabulating 1890 - Herman Hollerith won the competition for the processing equipment to assist in the 1890 US Census The Hollerith Tabulating Company, eventually became the Calculating-Tabulating-Recording (C-T-R) company in 1914, and eventually was renamed IBM in 1924.
Loop invariants In order to verify loops we often establish an assertion (boolean expression) that is true each time we reach a specific point in the loop. We call this assertion, a loop invariant
Assertions When ever the program reaches the top of the while loop, the assertion is true INIT BODY INVARIANT TEST
Example Write a method to compute an public static int power(int a , int n) You have 5 minutes
Possible solution public static double power(int a, int n) { double r = 1; double b = a; int i = n ; while (i>0){ if (i%2 == 0) { b = b * b; i = i / 2;} else { r = r * b; i--; } return r; }
Does it work? b i r a 100 1 a2 50 a4 25 24 a8 12 a16 6 a32 3 2 a36 a64 a100 Does it work? SURE! TRUST ME! Well, look at a100 if you don’t believe me! Note, less loops! Can you “prove” that it works?
What is the loop invariant? At the top of the while loop, it is true that r*bi = an It is? Well, at the top of the first loop r==1 b==a i==n
So, if it’s true at the start Even case rnew= rold bnew == (bold)2 inew==(iold)/2 Therefore, rnew * (bnew)i-new == rold * ((bold)2)i-old/2 == rold * ((bold)2)i-old == an
So, if it’s true at the start II Odd case rnew= rold*bold bnew == bold inew==iold-1 Therefore, rnew * (bnew)i-new == rold *bold* (bold)i-old-1 == rold * (bold)i-old == an
r*bi = an So, If it’s true at the start And every time in the loop, it remains true Then, it is true at the end r*bi = an And, i == 0 ( the loop ended) What do we know?
Correctness Proofs Proof are more valuable than testing Tests demonstrate limited correctness Proofs demonstrate correctness for all inputs For some time, people hoped that all formal logic would replace programming The naïve idea that “programming is a form of math” proved to be an oversimplification
Correctness Proofs Unfortunately, in practice, these methods never worked very well. Instead of buggy programs, people wrote buggy logic Nonetheless, the approach is useful for program analysis
The take away message? In the end, engineering and (process) management are at least as important as mathematics and logic for the successful completion of large software projects