1 / 12

Loop Invariants

Loop Invariants. General Notation. {r} T ; {inv : p } {bd : t } while B do S ; od {q}. require --- from init invariant inv variant var until exit loop body ensure --- end. Correctness Proof. p is initially established; that is {r}T{p} holds.

brit
Download Presentation

Loop Invariants

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Loop Invariants

  2. General Notation {r} T; {inv : p}{bd : t } whileBdo S; od {q} require --- frominit invariant inv variant var until exit loop body ensure --- end

  3. Correctness Proof • p is initially established;that is {r}T{p} holds. • p is a loop invariant;that is, {p /\ B}S{p} holds. • Upon loop termination q is true;that is, p /\ !B --> q • p implies t >= 0;that is p --> t >= 0 • t is decreased with each iteration; that is, {p /\ B /\ t = z}S{t < z} Correctness Termination

  4. proof steps (in other words) • The invariant is true at the beginning of the first loop iteration; • The invariant is maintained by one pass through the loop body; • The postcondition follows from the invariant and the exit condition; • The variant is always non-negative; • The variant decreases by at least one in every pass through the loop body;

  5. Integer Logarithm • The integer logarithm of n in base b is the largest integer l such that b^ln • ilog(2,10) = 3 • 2^3  10 • 2^4 > 10 • ilog(3, 90) = 4 • 3^4  90 • 3^5 > 90

  6. ? ?

  7. Invariant

  8. Step1: Invariant initially holds • Result=0; p=1 • b≥2 & n ≥1 • I1: b^0=p=1 • I2: p=1≤b^n • I3:p ≥1

  9. Step2: Invariant holds one pass in the loop • b^Result’=p’ & p’≥1 • p=p’*b, Result=Result’+1 • b^Result=b^(Result’+1)=b^Result’*b=p’*b=p (I1) • p’≤n  p=p’*b ≤ n*b (I2) • b≥2 & p’≥1  p=p’*b≥2≥1

  10. Step3: Invariant implies post • Reuslt1 is Result after the loop • b^Result1=p (I1) • p≤b*n (I2) & p>n (exit) • I1+exit: b^Result1>n • I2+I1:b^Result1≤b*n • Result1 = Result+1 • I1+exit: b^(Result+1)>n • I2+I1:b^(Result+1)≤b*n  b^Result≤n

  11. Step4: Variant non negative • I2: p ≤ b*n  0 ≤ b*n-p

  12. Step5: Variant decreases at least by 1 • b*n is a constant • p = p’*b, b≥2, p≥1 • p≥p’*2>p’ • b*n-p < b*n-p’

More Related