Short-circuit Logic

rusi rustompmody at gmail.com
Mon May 27 00:44:30 EDT 2013


On May 27, 5:40 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> On Sun, 26 May 2013 16:22:26 -0400, Roy Smith wrote:
> > In article <mailman.2196.1369599562.3114.python-l... at python.org>,
> >  Terry Jan Reedy <tjre... at udel.edu> wrote:
>
> >> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
>
> >> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
> >> >                  print("zero is not allowed")
>
> >> The reason for the order is to do the easy calculation first and the
> >> harder one only if the first passes.
>
> > This is a particularly egregious case of premature optimization.  You're
> > worried about how long it takes to execute abs(x)?  That's silly.
>
> I don't think it's a matter of premature optimization so much as the
> general principle "run code only if it needs to run". Hence, first you
> check the flag to decide whether or not you care whether x is near zero,
> and *only if you care* do you then check whether x is near zero.
>
> # This is silly:
> if x is near zero:
>     if we care:
>         handle near zero condition()
>
> # This is better:
> if we care:
>     if x is near zero
>         handle near zero condition()
>
> Not only is this easier to understand because it matches how we do things
> in the real life, but it has the benefit that if the "near zero"
> condition ever changes to become much more expensive, you don't have to
> worry about reordering the tests because they're already in the right
> order.
>
> --
> Steven

Three points:

3. These arguments are based on a certain assumption: that the inputs
are evenly distributed statistically.
If however that is not so, ie say:
"We-care" is mostly true
and
"x-is-near-zero" is more often false
then doing the near-zero test first would be advantageous

Well thats the 3rd point...

2. Nikalus Wirth deliberately did not use short-circuit boolean
operators in his languages because he found these kind of distinctions
to deteriorate into irrelevance and miss out the more crucial
questions of correctness

1. As Roy pointed out in his initial response to the OP:
"I dont understand your confusion... None of <the above> applies to
your example"
its not at all clear to me that anything being said has anything to do
with what the OP asked!



More information about the Python-list mailing list