2

I was wondering if anyone could help me answer this question. It is from a previous exam paper and I could do with knowing the answer ready for this years exam.

This question seems so simple that I am getting completely lost, what exactly is it asking for? Is the following algorithm to find maximum value correct?

 {P: x≥0 ∧ y≥0 ∧ z≥0 } 
 if (x > y && x > z) 
 max = x; 
 else if (y > x && y > z) 
 max = y; 
 else 
 max = z; 
 {Q: max≥x ∧ max≥y ∧ max≥z ∧ ( max=x ∨ max=y ∨ max=z )} 

The answer must be based on calculation of the weakest precondition for the algorithm.

How do you verify this? It seems to simple.

Thanks.

user2988649
  • 323
  • 2
  • 4
  • 12

1 Answers1

2

This question seems so simple that I am getting completely lost, what exactly is it asking for?

The question is asking for you to formally prove that the program behaves as specified, by the rigorous application of a set of rules decided on in advance (as opposed to reading the program and saying that it obviously works).

How do you verify this?

The program is as follows:

if (x > y && x > z) 
 max = x; 
else P1

with P1 a shorthand for if (y > x && y > z) max = y; else max = z;

So the program is basically an if-then-else. Hoare logic provides a rule for the if-then-else construct:

{B ∧ P} S {Q}   ,   {¬B ∧ P } T {Q}
----------------------------------
   {P} if B then S else T {Q}

Instanciating the general if-then-else rule for the program at hand:

{???}  max = x;  {Q}    ,    {???}  P1  {Q}
-------------------------------------------------------------------------------------
{true}  if (x > y && x > z) max = x; else P1  {Q: max≥x ∧ max≥y ∧ max≥z ∧ ( max=x ∨ max=y ∨ max=z)}

Can you complete the ??? placeholders?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
  • Should it be : {x > y && x > z} max = x; {Q} , {y > x && y > z,max = z} P1 {Q} And how do I calculate the weakest precondition ? Thank you for your time Pascal Cuoq ! I really appericiate it.... – user2988649 Apr 27 '14 at 11:56
  • @user2988649 Yes, you find yourself having to prove `{x > y && x > z} max = x; {Q}` on the left-hand side. On the right-hand side, you made a mistake when you applied `¬` to `x > y && x > z`. The result is not what you wrote: `¬ (x > y && x > z)` is equivalent to `x <= y || x <= z`. The weakest precondition for the program and for the provided postcondition is `true`. I already filled that in to make it easier for you. Following the weakest-precondition, you would fill in that part last from what has been filled in in the rest of the proof. – Pascal Cuoq Apr 27 '14 at 12:23
  • @user2988649 We are still trying to apply the if-then-else rule to the first if at this point. The generic if-then-else rule says `{¬B ∧ P } T {Q}`. – Pascal Cuoq Apr 27 '14 at 12:49