On Sun, 26 May 2013 04:11:56 -0700, Ahmed Abdulshafy wrote:

> I'm having a hard time wrapping my head around short-circuit logic that's
> used by Python, coming from a C/C++ background; so I don't understand why
> the following condition is written this way!>
> 
>      if not allow_zero and abs(x) < sys.float_info.epsilon:
>                 print("zero is not allowed")
> 
> The purpose of this snippet is to print the given line when allow_zero is
> False and x is 0.

I don't understand your confusion. The above is directly equivalent to the
following C code:

        if (!allow_zero && fabs(x) < DBL_EPSILON)
            printf("zero is not allowed\n");

In either case, the use of short-circuit evaluation isn't necessary here;
it would work just as well with a strict[1] "and" operator.

Short-circuit evaluation is useful if the second argument is expensive to
compute, or (more significantly) if the second argument should not be
evaluated if the first argument is false; e.g. if x is a pointer then:

        if (x && *x) ...

relies upon short-circuit evaluation to avoid dereferencing a null pointer.

On an unrelated note: the use of the "epsilon" value here is
almost certainly wrong. If the intention is to determine if the result of
a calculation is zero to within the limits of floating-point accuracy,
then it should use a value which is proportional to the values used in
the calculation.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to