CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.

Slides:



Advertisements
Similar presentations
Automated Theorem Proving Lecture 1. Program verification is undecidable! Given program P and specification S, does P satisfy S?
Advertisements

CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY Lecture 9 CS2110 – Spring 2015 We may not cover all this material.
Reasoning About Code; Hoare Logic, continued
1 CS March 2009 While loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim in two days: Th 7:30-9pm Uris Aud.
Copyright © 2006 Addison-Wesley. All rights reserved.1-1 ICS 410: Programming Languages Chapter 3 : Describing Syntax and Semantics Axiomatic Semantics.
ESC Java. Static Analysis Spectrum Power Cost Type checking Data-flow analysis Model checking Program verification AutomatedManual ESC.
1 CS100J October 06, 2005 For Loops Reading: Secs Quote for the Day: Perhaps the most valuable result of all education is the ability to make yourself.
CS 1110 Prelim III: Review Session 1. Info My name: Bruno Abrahao – We have two other TA’s in the room to help you individually Beibei Zhu Suyong Zhao.
1 Teaching the development of algorithms Teach skill, not only facts David Gries Computer Science Department Cornell University November 2004 DrJava is.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
1 Recitation 7. Developing loops Introduction. This recitation concerns developing loops using their invariants and bound functions. Your recitation instructor.
1 Assignment 6. Developing Loops Due on Tuesday, 30 October, by midnight (submitted electronically). Note that each question will be graded on the following.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Proving Program Correctness The Axiomatic Approach.
Computer Science School of Computing Clemson University Discrete Math and Reasoning about Software Correctness Murali Sitaraman
1 CS October 2008 The while loop and assertions Read chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Quotes for the Day:
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Reading and Writing Mathematical Proofs
1 “Not all recursive solutions are better than iterative solutions…” “… recursion, however, can provide elegantly simple solutions to problems of great.
1 Inference Rules and Proofs (Z); Program Specification and Verification Inference Rules and Proofs (Z); Program Specification and Verification.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
CSI 3125, Axiomatic Semantics, page 1 Axiomatic semantics The assignment statement Statement composition The "if-then-else" statement The "while" statement.
Search algorithms for vectors Jordi Cortadella Department of Computer Science.
Reasoning about programs March CSE 403, Winter 2011, Brun.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
CS November 2010 Developing array algorithms. Reading: Haikus (5-7-5) seen on Japanese computer monitors Yesterday it worked. Today it is.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
(c) , University of Washington18a-1 CSC 143 Java Searching and Recursion N&H Chapters 13, 17.
1 CS April 2010 while loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim 2. Thursday evening, 7:30PM Watch.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Dr. Naveed Riaz Design and Analysis of Algorithms 1 1 Formal Methods in Software Engineering Lecture # 26.
Loop Invariants and Binary Search Chapter 4.4, 5.1.
1 CS April 2010 while loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim 2. Thursday evening, 7:30PM Watch.
1 CS April 2009 Sorting: insertion sort, selection sort, quick sort Do exercises on pp to get familiar with concepts and develop skill.
1 CS1110 Lecture 16, 26 Oct 2010 While-loops Reading for next time: Ch (arrays) Prelim 2: Tu Nov 9 th, 7:30-9pm. Last name A-Lewis: Olin 155 Last.
1 CS100J 06 March 2008 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal pointI'm.
CS100A, Fall Review of loops 1 CS100A, Fall 1998, Review of Loops and Loop Invariants Some students are still having trouble understanding loop invariants.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2015.
Correctness issues and Loop invariants
CS100J 30 October 2007 Algorithms on arrays Reading: 8.3–8.5
Reasoning About Code.
Reasoning about code CSE 331 University of Washington.
Developing Loops from Invariants
CS October 2008 The while loop and assertions
Reasoning About Code; Hoare Logic
Testing change to a linked list
Axiomatic semantics Points to discuss: The assignment statement
Programming Languages and Compilers (CS 421)
Programming Languages 2nd edition Tucker and Noonan
Asymptotic complexity Searching/sorting
Output Variables {true} S {i = j} i := j; or j := i;
Binary Search and Loop invariants
Asymptotic complexity
CS November 2010 Developing array algorithms. Reading:
Searching and Sorting Hint at Asymptotic Complexity
Searching and Sorting Hint at Asymptotic Complexity
Developing loops from invariants
CS100A Lecture 25 1 December 1998 Chance to replace grade on Prelim 3, Question 2. Everyone is expected to be in lecture on Thursday, 3 December.
CS100J Nov 04, 2003 Arrays. Reading: 8
Programming Languages and Compilers (CS 421)
CS100A Sections Dec Loop Invariant Review C Review and Example
Developing Loops from Invariants
Programming Languages 2nd edition Tucker and Noonan
Searching and Sorting Hint at Asymptotic Complexity
Searching and Sorting Hint at Asymptotic Complexity
CS October 2010 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal point I'm.
Presentation transcript:

CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014

About A2 and feedback. Recursion S2 has been graded. If you got 30/30, you will probably have no feedback. If you got less than full credit, there should be feedback showing you which function(s) is incorrect. If you don’t see feedback, ask for a regrade on the CMS. Please don’t anyone asking for a regrade. We will put on the course website some recursive functions for you to write, to get practice with recursion. This will not be an assignment. But if you know you need practice, practice! 2

Preconditions and Postconditions 3 {x >= 0} x= x + 1; {x > 0} precondition Q statement S postcondition R Write it like this: {Q} S {R} Called a Hoare Triple, after Sir Tony Hoare. Introduced notation in a paper in {Q} S {R} is a true-false statement. Read it as follows: Execution of S begun in a state in which Q is true is guaranteed to terminate, and in a state in which R is true. This Hoare triple is true! In a Java program, you have to make have to make the assertion comments: // {x >= 0}

Preconditions and Postconditions 4 {x >= 0} x= x + 1; {x = 0} precondition Q statement S postcondition R Write it like this: {Q} S {R} Called a Hoare Triple, after Sir Tony Hoare. Introduced notation in a paper in {Q} S {R} is a true-false statement. Read it as follows: Execution of S begun in a state in which Q is true is guaranteed to terminate, and in a state in which R is true. This Hoare triple is false! In a Java program, you have to make have to make the assertion comments: // {x >= 0}

Annotating more completely with assertions 5 /** Return b^c. Precondition 0 <= c */ public static int exp(int b, int c) { int ans; if (c == 0) { {0 = c} ans= 1; {ans = b^c} Hoare triples } else { {0 < c} ans= b * exp(b, c-1); {ans = b^c} } {ans = b^c} return ans; } The blue things are assertions –pre- and post-conditions. They help prove that IF 0 <= c at the beginning, ans = b^c before the return. {0 <= c} precondition!

Axiomatic definition of a language 6 /** Return b^c. Precondition 0 <= c */ public static int exp(int b, int c) { int ans; if (c == 0) { {0 = c} ans= 1; {ans = b^c} } else { {0 < c} ans= b * exp(b, c-1); {ans = b^c} } {ans = b^c} return ans; } Hoare gave rules for deciding whether a Hoare triple {Q} S {R} was correct. Defined the language in terms of correctness instead of execution. See that in later courses. We concentrate on one aspect: how to “prove” loops correct. {0 <= c}

Axiomatic definition of a language 7 /** Return b^c. Precondition 0 <= c */ public static int exp(int b, int c) { int ans; if (c == 0) { {0 = c} ans= 1; {ans = b^c} } else { {0 < c} ans= b * exp(b, c-1); {ans = b^c} } {ans = b^c} return ans; } Hoare gave rules for deciding whether a Hoare triple {Q} S {R} was correct. Defined the language in terms of correctness instead of execution. See that in later courses. We concentrate on one aspect: how to “prove” loops correct. {0 <= c}

Reason for introducing loop invariants 8 Given c >= 0, store b^c in x z= 1; x= b; y= c; while (y != 0) { if (y is even) { x= x*x; y= y/2; } else { z= z*x; y= y - 1; } {z = b^c} Algorithm to compute b^c. Can’t understand any piece of it without understanding everything. In fact, only way to get a handle on it is to execute it on some test case. Need to understand initialization without looking at any other code. Need to understand condition y != 0 without looking at method body Etc.

Invariant: is true before and after each iteration 9 initialization; // invariant P while (B) {S} “invariant” means unchanging. Loop invariant: an assertion —a true-false statement— that is true before and after each iteration of the loop —every time B is to be evaluated. Help us understand each part of loop without looking at all other parts. init B S true false {P} {P and ! B} Upon termination, we know P true, B false

Simple example to illustrate methodology 10 Store sum of 0..n in s Precondition: n >= 0 // { n >= 0} k= 1; s= 0; // inv: s = sum of 0..k-1 && // 0 <= k <= n+1 while (k <= n) { s= s + k; k= k + 1; } {s = sum of 0..n} First loopy question. Does it start right? Does initialization make invariant true? Yes! s = sum of 0..k-1 = 0 = sum of = 0 = sum of 0..0 We understand initialization without looking at any other code

Simple example to illustrate methodology 11 Store sum of 0..n in s Precondition: n >= 0 // { n >= 0} k= 1; s= 0; // inv: s = sum of 0..k-1 && // 0 <= k <= n+1 while (k <= n) { s= s + k; k= k + 1; } {s = sum of 0..n} Second loopy question. Does it stop right? Upon termination, is postcondition true? Yes! inv && ! k <= n => inv && k = n+1 => s = sum of 0..n+1-1 We understand that postcondition is true without looking at init or repetend

Simple example to illustrate methodology 12 Store sum of 0..n in s Precondition: n >= 0 // { n >= 0} k= 1; s= 0; // inv: s = sum of 0..k-1 && // 0 <= k <= n+1 while (k <= n) { s= s + k; k= k + 1; } {s = sum of 0..n} Third loopy question. Progress? Does the repetend make progress toward termination? Yes! Each iteration increases k, and when it gets larger than n, the loop terminates We understand that there is no infinite looping without looking at init and focusing on ONE part of the repetend.

Simple example to illustrate methodology 13 Store sum of 0..n in s Precondition: n >= 0 // { n >= 0} k= 1; s= 0; // inv: s = sum of 0..k-1 && // 0 <= k <= n+1 while (k <= n) { s= s + k; k= k + 1; } {s = sum of 0..n} Fourth loopy question. Invariant maintained by each iteration? Is this Hoare triple true? {inv && k <= n} repetend {inv} Yes! {s = sum of 0..k-1} s= s + k; {s = sum of 0..k} k= k+1; {s = sum of 0..k-1}

4 loopy questions to ensure loop correctness 14 {precondition Q} init; // invariant P while (B) { S } {R} First loopy question; Does it start right? Is {Q} init {P} true? Second loopy question: Does it stop right? Does P && ! B imply R? Third loopy question: Does repetend make progress? Will B eventually become false? Fourth loopy question: Does repetend keep invariant true? Is {P && ! B} S {P} true? Four loopy questions: if answered yes, algorithm is correct.

Note on ranges m..n 15 Range m..n contains n+1–m ints: m, m+1,..., n (Think about this as "follower (n+1) minus first (m)”) 2..4 contains 2, 3, 4: that is – 2 = 3 values 2..3 contains 2, 3: that is – 2 = 2 values 2..2 contains 2: that is – 2 = 1 value 2..1 contains : that is – 2 = 0 values Convention: notation m..n implies that m <= n+1 Assume convention even if it is not mentioned! If m is 1 larger than n, the range has 0 values b m n array segment b[m..n]:

Can’t understand this example without invariant! 16 Given c >= 0, store b^c in z z= 1; x= b; y= c; // invariant y >= 0 && // z*x^y = b^c while (y != 0) { if (y is even) { x= x*x; y= y/2; } else { z= z*x; y= y - 1; } {z = b^c} First loopy question. Does it start right? Does initialization make invariant true? Yes! z*x^y = 1*b^c = b^c We understand initialization without looking at any other code

For loopy questions to reason about invariant 17 Given c >= 0, store b^c in x z= 1; x= b; y= c; while (y != 0) { if (y is even) { x= x*x; y= y/2; } else { z= z*x; y= y - 1; } {z = b^c} Second loopy question. Does it stop right? When loop terminates, is z = b^c? Yes! Take the invariant, which is true, and use fact that y = 0: z*x^y = b^c = z*x^0 = b^c = z = b^c We understand loop condition without looking at any other code // invariant y >= 0 AND // z*x^y = b^c

For loopy questions to reason about invariant 18 Given c >= 0, store b^c in x z= 1; x= b; y= c; // invariant y >= 0 AND // z*x^y = b^c while (y != 0) { if (y is even) { x= x*x; y= y/2; } else { z= z*x; y= y - 1; } {z = b^c} Third loopy question. Does repetend make progress toward termination? Yes! We know that y > 0 when loop body is executed. The loop body decreases y. We understand progress without looking at initialization

For loopy questions to reason about invariant 19 Given c >= 0, store b^c in x z= 1; x= b; y= c; // invariant y >= 0 AND // z*x^y = b^c while (y != 0) { if (y is even) { x= x*x; y= y/2; } else { z= z*x; y= y - 1; } {z = b^c} Fourth loopy question. Does repetend keep invariant true? Yes! Because of properties: For y even, x^y = (x*x)^(y/2) z*x^y = z*x*x^(y-1) We understand invariance without looking at initialization

Designing while-loops or for-loops 20 Many loops process elements of an array b (or a String, or any list) in order: b[0], b[1], b[2], … If the postcondition is R: b[0..b.length-1] has been processed Then in the beginning, nothing has been processed, i.e. b[0..-1] has been processed After k iterations, k elements have been processed: P: b[0..k-1] has been processed invariant P: b processed not processed 0 k b.length

Developing while-loops (or for loops) 21 Task: Process b[0..b.length-1] {R: b[0..b.length-1] has been processed} Replace b.length in postcondition by fresh variable k to get invariant b[0..k-1] has been processed inv P:b processed not processed 0 k b.length or draw it as a picture k= 0; {inv P} while ( ) { } k != b.length k= k + 1; // progress toward termination Process b[k]; // maintain invariant

Developing while-loops (or for loops) 22 Task: Process b[0..b.length-1] {R: b[0..b.length-1] has been processed} inv P:b processed not processed 0 k b.length k= 0; {inv P} while ( ) { } k != b.length k= k + 1; // progress toward termination Process b[k]; // maintain invariant Most loops that process the elements of an array in order will have this loop invariant and will look like this.

Counting the number of zeros in b. Start with last program and refine it for this task 23 Task: Set s to the number of 0’s in b[0..b.length-1] {R: s = number of 0’s in b[0..b.length-1]} inv P:b s = # 0’s here not processed 0 k b.length k= 0; {inv P} while ( ) { } k != b.length k= k + 1; // progress toward termination Process b[k]; // maintain invariant s= 0; if (b[k] == 0) s= s + 1;

Be careful. Invariant may require processing elements in reverse order! 24 inv P:b processed not processed 0 k b.length This invariant forces processing from beginning to end inv P:b not processed processed 0 k b.length This invariant forces processing from end to beginning

Process elements from end to beginning 25 inv P:b not processed processed 0 k b.length {R: b[0..b.length-1] is processed} k= b.length–1; // how does it start? while (k >= 0) { // how does it end? } k= k – 1; // how does it make progress? Process b[k]; // how does it maintain invariant?

Process elements from end to beginning 26 inv P:b not processed processed 0 k b.length {R: b[0..b.length-1] is processed} k= b.length–1; while (k >= 0) { } k= k – 1; Process b[k]; Heads up! It is important that you can look at an invariant and decide whether elements are processed from beginning to end or end to beginning! For some reason, some students have difficulty with this. A question like this could be on the prelim!

Develop binary search for v in sorted array b 27 ? pre: b 0 b.length post: b 0 h b.length v pre: b b.length Example: If v is 4, 5, or 6, h is 5 If v is 7 or 8, h is 6 If v in b, h is index of rightmost occurrence of v. If v not in b, h is index before where it belongs.

Develop binary search in sorted array b for v 28 ? pre: b 0 b.length post: b 0 h b.length v Get loop invariant by combining pre- and post- conditions, adding variable t to mark the other boundary inv: b 0 h t b.length v Store a value in h to make this true:

How does it start (what makes the invariant true)? 29 ? pre: b 0 b.length inv: b 0 h t b.length v Make first and last partitions empty: h= -1; t= b.length;

When does it end (when does invariant look like postcondition)? 30 inv: b 0 h t b.length v h= -1; t= b.length; while ( ) { } post: b 0 h b.length v Stop when ? section is empty. That is when h = t-1. Therefore, continue as long as h != t-1. h != t-1

How does body make progress toward termination (cut ? in half) and keep invariant true? 31 inv: b 0 h t b.length v h= -1; t= b.length; while ( h != t-1 ) { } Let e be index of middle value of ? Section. Maybe we can set h or t to e, cutting ? section in half b 0 h e t b.length v int e= (h+t)/2;

How does body make progress toward termination (cut ? in half) and keep invariant true? 32 inv: b 0 h t b.length v h= -1; t= b.length; while ( h != t-1 ) { int e= (h+t)/2; } b 0 h e t b.length v if (b[e] <= v) h= e; If b[e] <= v, then so is every value to its left, since the array is sorted. Therefore, h= e; keeps the invariant true. b 0 h e t b.length v

How does body make progress toward termination (cut ? in half) and keep invariant true? 33 inv: b 0 h t b.length v h= -1; t= b.length; while ( h != t-1 ) { int e= (h+t)/2; if (b[e] <= v) h= e; } b 0 h e t b.length v else t= e; If b[e] > v, then so is every value to its right, since the array is sorted. Therefore, t= e; keeps the invariant true. b 0 h e t b.length v > v