by feoren · 2y ago · 0 comments
prove (or at least test conclusively) that for all integer x, the output y of the following function is always even:
y = x^2 + x + 2
There is essentially no way to prove this for all x by simply testing all integers. If your integers are 64-bit, you don't have enough time in the lifespan of the universe.On the other hand, you could simply reason through the cases: if x is even, then all terms are even. If x is odd, then x^2 is also odd, and x^2 + x = odd + odd = even. So you're done.
This is what people mean when they say "tests don't prove your code is correct" -- it's almost always better to be able to read code and prove (to some degree) that it's correct. It's really nothing like static types, which are also constructive proofs that your code is not incorrect in specific ways. (That is: it proves that your code is not [incorrect in specific ways], not that your code is [not incorrect].)
Once you prove your code correct, you can often write efficient tests with cases at the correct boundary points to make sure that proof stays correct as the code changes.
class N(int):
def __init__(self, z: int):
assert z > 0
super().__init__(z)
def log2(n: N) -> float:
…
log2(N(32)) # 5.0
log2(32) # type error
log2(N(-32)) # runtime error
You are still relying on the runtime to detect errors and it’s annoying to have to cast all ints to Ns, but you at least won’t ever take the log of a negative number.``` x = N(2) x -= 10 ```
I think x still winds up being less than 0 here?
Its probably easier just to add an "assert" with a friendly message at the start of the log function.
Hence why he states it is formal verification for the "unwashed masses". The "washed" will use a language with a type system that is advanced enough to express a formal proof, but most people can't hack it, and thus use languages with incomplete type systems and use testing to try and fill in the gaps.