Short-circuit Logic

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 31 01:13:51 EDT 2013


On Fri, 31 May 2013 00:03:13 +0300, Carlos Nepomuceno wrote:

> ----------------------------------------
>> From: steve+comp.lang.python at pearwood.info Subject: Re: Short-circuit
>> Logic
>> Date: Thu, 30 May 2013 05:42:17 +0000 To: python-list at python.org
> [...]
>> Here's another way, mathematically equivalent (although not necessarily
>> equivalent using floating point computations!) which avoids the
>> divide-by- zero problem:
>>
>> abs(a - b) < epsilon*a
> 
> That's wrong! If abs(a) < abs(a-b)/epsilon you will break the
> commutative law. For example:

What makes you think that the commutative law is relevant here?

Many things break the commutative law, starting with division and 
subtraction:

    20 - 10 != 10 - 20

    1/2 != 2/1

Most comparison operators other than equality and inequality:

    (23 < 42) != (42 < 23)

String concatenation:

    "Hello" + "World" != "World" + "Hello"

Many operations in the real world:

    put on socks, then shoes != put on shoes, then socks.


But you are correct that approximately-equal using *relative* error is 
not commutative. (Absolute error, on the other hand, is commutative.) As 
I said, any form of "approximate equality" has gotchas. But this gotcha 
is simple to overcome: 

    abs(a -b) < eps*max(abs(a), abs(b))

(Knuth's "approximately equal to" which you give.)


> This discussion reminded me of TAOCP and I paid a visit and bring the
> following functions:

"TAOCP"?


-- 
Steven



More information about the Python-list mailing list