CORRECTNESS ISSUES AND LOOP INVARIANTS

Similar documents
CORRECTNESS ISSUES AND LOOP INVARIANTS

CS211 Spring 2004 Lecture 06 Loops and their invariants. Software engineering reason for using loop invariants

CS 1110: Introduction to Computing Using Python Loop Invariants

Prelim 1. Solution. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY

Prelim 1. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer. OO Recursion Loop invariants Max Score Grader

Prelim 1. Solution. CS 2110, 14 March 2017, 5:30 PM Total Question Name Short answer

CS Lecture 19: Loop invariants

ASYMPTOTIC COMPLEXITY

Prelim 1. CS 2110, 14 March 2017, 5:30 PM Total Question Name Short answer. OO Recursion Loop invariants Max Score Grader

SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY

ASYMPTOTIC COMPLEXITY

Announcements SORTING. Prelim 1. Announcements. A3 Comments 9/26/17. This semester s event is on Saturday, November 4 Apply to be a teacher!

SORTING 9/26/18. Prelim 1. Prelim 1. Why Sorting? InsertionSort. Some Sorting Algorithms. Tonight!!!! Two Sessions:

Lecture 24: Loop Invariants

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

SORTING. Insertion sort Selection sort Quicksort Mergesort And their asymptotic time complexity

Backward Reasoning: Rule for Assignment. Backward Reasoning: Rule for Sequence. Simple Example. Hoare Logic, continued Reasoning About Loops

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

Plan of the lecture. Quick-Sort. Partition of lists (or using extra workspace) Quick-Sort ( 10.2) Quick-Sort Tree. Partitioning arrays

isinstance and While Loops

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop

CSE 331 Software Design and Implementation. Lecture 3 Loop Reasoning

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

Hoare Logic: Proving Programs Correct

CS 1110: WORKED EXAMPLES REGARDING LOOPS AND INVARIANTS

Lecture 25. Sequence Algorithms (Continued)

Lecture 22. While Loops

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

CS 1110 Final, December 9th, Question Points Score Total: 100

CS 1110, LAB 13: SEQUENCE ALGORITHMS

Question 0. (out of 01) Question 1. (out of 10) Question 2. (out of 12) Question 3. (out of 12) Question 4. (out of 12) Question 5.

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

Basic Techniques. Recursion. Today: Later on: Recursive methods who call themselves directly or indirectly.

Formal Methods. CITS5501 Software Testing and Quality Assurance

Softwaretechnik. Program verification. Software Engineering Albert-Ludwigs-University Freiburg. June 30, 2011

Lecture 6 Binary Search

Arguing for program correctness and writing correct programs

Reasoning About Imperative Programs. COS 441 Slides 10

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0

(Refer Slide Time: 01.26)

You must include this cover sheet. Either type up the assignment using theory4.tex, or print out this PDF.

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Recall our recursive multiply algorithm:

Lecture Notes: Hoare Logic

CS 1110 Final, December 8th, Question Points Score Total: 100

Topics Introduction to Microprocessors

Introduction to Axiomatic Semantics

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24

Correctness of specifications. Correctness. Correctness of specifications (2) Example of a Correctness Proof. Testing versus Correctness Proofs

CITS5501 Software Testing and Quality Assurance Formal methods

Hardware versus software

Checking Program Properties with ESC/Java

Reasoning about programs

Last time. Reasoning about programs. Coming up. Project Final Presentations. This Thursday, Nov 30: 4 th in-class exercise

Iteration and For Loops

Main Goal. Language-independent program verification framework. Derive program properties from operational semantics

Principles of Program Analysis. Lecture 1 Harry Xu Spring 2013

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

Specifications. Prof. Clarkson Fall Today s music: Nice to know you by Incubus

Exam I Principles of Imperative Computation, Summer 2011 William Lovas. May 27, 2011

Structure and Interpretation of Computer Programs

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Sorting and Searching

CS 1110 Final, December 8th, Question Points Score Total: 100

6. Hoare Logic and Weakest Preconditions

Lecture Notes on Quicksort

A CRASH COURSE IN SEMANTICS

CSC 273 Data Structures

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016

Overview. Probabilistic Programming. Dijkstra s guarded command language: Syntax. Elementary pgcl ingredients. Lecture #4: Probabilistic GCL

An Annotated Language

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Review Session. CS2110 Prelim #1 3/8/15. Primitive types vs classes. Default values. Wrapper Classes (Boxing) Strings are immutable.

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

Lectures 20, 21: Axiomatic Semantics

You have 45 minutes to work on this exam. It is a "closed-book/closed-notes" test.

Axiomatic Rules. Lecture 18: Axiomatic Semantics & Type Safety. Correctness using Axioms & Rules. Axiomatic Rules. Steps in Proof

Lecture Notes on Quicksort

Review: Hoare Logic Rules

Structure and Interpretation of Computer Programs

Part II. Hoare Logic and Program Verification. Why specify programs? Specification and Verification. Code Verification. Why verify programs?

CS2104 Prog. Lang. Concepts

Lecture Notes for Chapter 2: Getting Started

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Binary Search. Roland Backhouse February 5th, 2001

Prelim 1, Solution. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha

Midterm I Exam Principles of Imperative Computation Frank Pfenning. February 17, 2011

CSE373 Fall 2013, Midterm Examination October 18, 2013

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

Warm-Up Problem. 1. What is the definition of a Hoare triple satisfying partial correctness? 2. Recall the rule for assignment: x (assignment)

COMP 161 Lecture Notes 16 Analyzing Search and Sort

syntax tree - * * * * * *

CSE11 Lecture 20 Fall 2013 Recursion

CIS 500 Software Foundations. Final Exam. May 3, Answer key

Program Verification. Aarti Gupta

ASTS, GRAMMARS, PARSING, TREE TRAVERSALS. Lecture 14 CS2110 Fall 2018

Transcription:

Aout A2 and feedack. Recursion 2 CORRECTNESS ISSUES AND LOOP INVARIANTS S2 has een graded. If you got 30/30, you will proaly have no feedack. If you got less than full credit, there should e feedack showing you which function(s) is incorrect. If you don t see feedack, ask for a regrade on the CMS. Please don t email anyone asking for a regrade. We will put on the course wesite some recursive functions for you to write, to get practice with recursion. This will not e an assignment. But if you know you need practice, practice! Lecture 8 CS2110 Fall 2014 Preconditions and Postconditions Preconditions and Postconditions 3 4 precondition Q statement S postcondition R {x >= 0 x= x + 1; {x > 0 This Hoare triple is true! precondition Q statement S postcondition R {x >= 0 x= x + 1; {x = 0 This Hoare triple is false! Write it like this: {Q S {R Called a Hoare Triple, after Sir Tony Hoare. Introduced notation in a paper in 1969. In a Java program, you have to make have to make the assertion comments: // {x >= 0 {Q S {R is a true-false statement. Read it as follows: Execution of S egun in a state in which Q is true is guaranteed to terminate, and in a state in which R is true. Write it like this: {Q S {R Called a Hoare Triple, after Sir Tony Hoare. Introduced notation in a paper in 1969. In a Java program, you have to make have to make the assertion comments: // {x >= 0 {Q S {R is a true-false statement. Read it as follows: Execution of S egun in a state in which Q is true is guaranteed to terminate, and in a state in which R is true. Annotating more completely with assertions Axiomatic definition of a language 5 /** Return ^c. Precondition 0 <= c */ pulic static int exp(int, int c) { {0 <= c precondition! int ans; if (c == 0) { {0 = c ans= 1; {ans = ^c Hoare triples else { {0 < c ans= * exp(, c-1); {ans = ^c {ans = ^c The lue things are assertions pre- and return ans; post-conditions. They help prove that IF 0 <= c at the eginning, ans = ^c efore the return. 6 /** Return ^c. Precondition 0 <= c */ pulic static int exp(int, int c) { {0 <= c int ans; Hoare gave rules for deciding if (c == 0) { whether a Hoare triple {Q S {0 = c ans= 1; {ans = ^c else { {0 < c ans= * exp(, c-1); {ans = ^c {ans = ^c return ans; {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. 1

Axiomatic definition of a language Reason for introducing loop invariants 7 /** Return ^c. Precondition 0 <= c */ pulic static int exp(int, int c) { {0 <= c int ans; Hoare gave rules for deciding if (c == 0) { whether a Hoare triple {Q S {0 = c ans= 1; {ans = ^c else { {0 < c ans= * exp(, c-1); {ans = ^c {ans = ^c return ans; {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. 8 Given c >= 0, store ^c in x z= 1; x= ; y= c; else { {z = ^c Algorithm to compute ^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 ody Etc. Invariant: is true efore and after each iteration 9 initialization; // invariant P while (B) {S Upon termination, we know P true, B false {P true init B S false {P and! B invariant means unchanging. Loop invariant: an assertion a true-false statement that is true efore and after each iteration of the loop every time B is to e evaluated. Help us understand each part of loop without looking at all other parts. 10 // { n >= 0 // s = sum of 0..k-1 && {s = sum of 0..n First loopy question. Does it start right? Does initialization make invariant true? s = sum of 0..k-1 = <sustitute initialization> 0 = sum of 0..1-1 = <arithmetic> 0 = sum of 0..0 We understand initialization without looking at any other code 11 // { n >= 0 // s = sum of 0..k-1 && {s = sum of 0..n Second loopy question. Does it stop right? Upon termination, is postcondition true? inv &&! k <= n => <look at inv> inv && k = n+1 => <use inv> s = sum of 0..n+1-1 We understand that postcondition is true without looking at init or repetend 12 // { n >= 0 // s = sum of 0..k-1 && {s = sum of 0..n Third loopy question. Progress? Does the repetend make progress toward termination? 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. 2

4 loopy questions to ensure loop correctness 13 // { n >= 0 // s = sum of 0..k-1 && {s = sum of 0..n Fourth loopy question. Invariant maintained y each iteration? Is this Hoare triple true? {inv && k <= n repetend {inv {s = sum of 0..k-1 {s = sum of 0..k k= k+1; {s = sum of 0..k-1 14 {precondition Q init; // invariant P while (B) { S {R Four loopy questions: if answered yes, algorithm is correct. 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 ecome false? Fourth loopy question: Does repetend keep invariant true? Is {P &&! B S {P true? Note on ranges m..n Can t understand this example without invariant! 15 Range m..n contains n+1 m ints: m, m+1,..., n (Think aout this as "follower (n+1) minus first (m) ) 2..4 contains 2, 3, 4: that is 4 + 1 2 = 3 values 2..3 contains 2, 3: that is 3 + 1 2 = 2 values 2..2 contains 2: that is 2 + 1 2 = 1 value 2..1 contains : that is 1 + 1 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 array segment [m..n]: m n 16 Given c >= 0, store ^c in z z= 1; x= ; y= c; // invariant y >= 0 && // z*x^y = ^c else { {z = ^c First loopy question. Does it start right? Does initialization make invariant true? z*x^y = <sustitute initialization> 1*^c = <arithmetic> ^c We understand initialization without looking at any other code For loopy questions to reason aout invariant For loopy questions to reason aout invariant 17 Given c >= 0, store ^c in x z= 1; x= ; y= c; // invariant y >= 0 AND // z*x^y = ^c else { {z = ^c Second loopy question. Does it stop right? When loop terminates, is z = ^c? Take the invariant, which is true, and use fact that y = 0: z*x^y = ^c = <y = 0> z*x^0 = ^c = <arithmetic> z = ^c We understand loop condition without looking at any other code 18 Given c >= 0, store ^c in x z= 1; x= ; y= c; // invariant y >= 0 AND // z*x^y = ^c else { {z = ^c Third loopy question. Does repetend make progress toward termination? We know that y > 0 when loop ody is executed. The loop ody decreases y. We understand progress without looking at initialization 3

19 For loopy questions to reason aout invariant Given c >= 0, store ^c in x z= 1; x= ; y= c; // invariant y >= 0 AND // z*x^y = ^c else { {z = ^c Fourth loopy question. Does repetend keep invariant true? 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 20 Designing while-loops or for-loops Many loops process elements of an array (or a String, or any list) in order: [0], [1], [2], If the postcondition is R: [0...length-1] has een processed Then in the eginning, nothing has een processed, i.e. [0..-1] has een processed After k iterations, k elements have een processed: P: [0..k-1] has een processed 0 k.length invariant P: processed not processed 21 Developing while-loops (or for loops) Replace.length in postcondition Task: Process [0...length-1] y fresh variale k to get invariant k= 0; [0..k-1] has een processed {inv P while ( k!=.length ) { or draw it as a picture Process [k]; // maintain invariant // progress toward termination {R: [0...length-1] has een processed 22 Developing while-loops (or for loops) Task: Process [0...length-1] k= 0; {inv P while ( k!=.length ) { Process [k]; // maintain invariant // progress toward termination {R: [0...length-1] has een processed Most loops that process the elements of an array in order will have this loop invariant and will look like this. 0 k.length inv P: processed not processed 0 k.length inv P: processed not processed 23 Counting the numer of zeros in. Start with last program and refine it for this task 24 Be careful. Invariant may require processing elements in reverse order! Task: Set s to the numer of 0 s in [0...length-1] k= 0; s= 0; {inv P while ( k!=.length ) { Process if ([k] == [k]; 0) s= // s + maintain 1; invariant // progress toward termination {R: s = numer of 0 s in [0...length-1] This invariant forces processing from eginning to end 0 k.length inv P: processed not processed This invariant forces processing from end to eginning 0 k.length 0 k.length inv P: not processed processed inv P: s = # 0 s here not processed 4

Process elements from end to eginning Process elements from end to eginning 25 k=.length 1; // how does it start? while (k >= 0) { // how does it end? Process [k]; // how does it maintain invariant? k= k 1; // how does it make progress? 26 k=.length 1; while (k >= 0) { Process [k]; k= k 1; Heads up! It is important that you can look at an invariant and decide whether elements are processed from eginning to end or end to eginning! For some reason, some students have difficulty with this. A question like this could e on the prelim! {R: [0...length-1] is processed {R: [0...length-1] is processed 0 k.length 0 k.length inv P: not processed processed inv P: not processed processed Develop inary search for v in sorted array Develop inary search in sorted array for v 27 pre: 0.length? 28 pre: 0.length? post: Example: pre: 0 h.length <= v > v 0 4 5 6 7.length 2 2 4 4 4 4 7 9 9 9 9 If v is 4, 5, or 6, h is 5 If v is 7 or 8, h is 6 If v in, h is index of rightmost occurrence of v. If v not in, h is index efore where it elongs. Store a value in h to make this true: 0 h.length post: <= v > v Get loop invariant y comining pre- and postconditions, adding variale t to mark the other oundary 0 h t.length How does it start (what makes the invariant true)? When does it end (when does invariant look like postcondition)? 29 pre: 0.length? 30 post: 0 h.length <= v > v 0 h t.length 0 h t.length Make first and last partitions empty: h= -1; t=.length; h= -1; t=.length; Stop when? section is empty. That is when h = t-1. Therefore, continue as long as h!= t-1. 5

How does ody make progress toward termination (cut? in half) and keep invariant true? How does ody make progress toward termination (cut? in half) and keep invariant true? 31 h= -1; t=.length; int e= (h+t)/2; 0 h t.length 0 h e t.length Let e e index of middle value of? Section. Maye we can set h or t to e, cutting? section in half 32 h= -1; t=.length; int e= (h+t)/2; if ([e] <= v) h= e; 0 h t.length 0 h e t.length <= v?? > v 0 h e t.length <= v If [e] <= v, then so is every value to its left, since the array is sorted. Therefore, h= e; keeps the invariant true. How does ody make progress toward termination (cut? in half) and keep invariant true? 33 0 h t.length h= -1; t=.length; int e= (h+t)/2; if ([e] <= v) h= e; else t= e; 0 h e t.length <= v?? > v 0 h e t.length > v If [e] > v, then so is every value to its right, since the array is sorted. Therefore, t= e; keeps the invariant true. 6