Short-circuit Logic

Carlos Nepomuceno carlosnepomuceno at outlook.com
Thu May 30 19:06:09 EDT 2013


----------------------------------------
> From: oscar.j.benjamin at gmail.com
> Date: Thu, 30 May 2013 23:57:28 +0100
> Subject: Re: Short-circuit Logic
> To: carlosnepomuceno at outlook.com
> CC: python-list at python.org
>
> On 30 May 2013 22:03, Carlos Nepomuceno <carlosnepomuceno at outlook.com> wrote:
>>> 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.
>
> There is no commutative law for relative tolerance floating point
> comparisons. If you want to compare with a relative tolerance then you
> you should choose carefully what your tolerance is to be relative to
> (and how big your relative tolerance should be).

Off course there is! It might not suite your specific needs though.

I'll just quote Knuth because it's pretty damn good:

"A. An axiomatic approach. Although the associative law is not valid, the commutative law

u (+) v == v (+) u     (2)

does hold, and this law can be a valuable conceptual asset in programming and in the analysis of programs. This example suggests that we should look for
important laws that are satified by (+), (-), (*), and (/); it is not unreasonable to say that floating point routines should be designed to preserve as many of the ordinary mathematical laws as possible. If more axioms are valid, it becomes easier to write good programs, and programs also become more portable from
machine to machine."
TAOCP, Vol .2, p. 214


> In some applications it's obvious which of a or b you should use to
> scale the tolerance but in others it is not or you should compare with
> something more complex. For an example where it is obvious, when
> testing numerical code I might write something like:
>
> eps = 1e-7
> true_answer = 123.4567879
> estimate = myfunc(5)
> assert abs(estimate - true_answer) < eps * abs(true_answer)
>
>
> Oscar 		 	   		  


More information about the Python-list mailing list