如何证明algorithm是正确的

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/cuidiwhere/article/details/79651650

前记:数据库hw3里有一个问题,让证明textbook里某个算法是correct的。第一反应觉得这个题目好奇怪,教材上给的算法肯定是正确的啊,有什么好证明的。冷静一想,自己太naive了。 于是在网上找了很多相关的资料,整理如下。

Scheme: 

1. All cases are covered: completeness 

Show all possible inputs are processed by the algorithm, may be trivial 

2. For a given (arbitrary) case, it is correctly processed: correctness 

May need to cover individually all branches/cases of the algorithm 

For each case, show the processing generates the expected output 

3. n all cases, the algorithm exits: termination

Example:

Def naive(a, b): 

x = a; y = b

z = 0

  while x > 0:

z = z + y

x = x - 1

return z

Prove the correctness of naive(a, b) 

        loop invariant:  naive(a, b) = ab , ab = xy + z

Base case: 

    First time through, x = a, y = b, z = 0

    ab = xy + z =  ab + 0 (correct! Loop invariant holds on loop entry )

Inductive step:

    if ab = xy + z before

    then ab = x’y’ + z’ after

    According to the algorithm, we could get:

    x’ = x-1, y’ = y, z’ = z+y

    x’y’ + z’ = (x-1)y + (z+y) = xy + z = ab (correct!)

We know ab=xy + z, so? (terminal)

    x = 0,  xy + z = ab

    0*y + z = ab   ==> z = ab

Reference: 

1.  http://www-inst.cs.berkeley.edu/~cs170/fa14/tutorials/tutorial1.pdf

  重点1:why we use inductive? 

  重点2: 1)  construct a loop invariant;  2) prove that loop invariant is inductive;  3) prove correctness property using loop invariant

2.  http://web.cs.ucla.edu/~pouchet/lectures/doc/888.11.algo.6.pdf

猜你喜欢

转载自blog.csdn.net/cuidiwhere/article/details/79651650