[Python-3000] Math in Python 3.0

Tim Peters tim.peters at gmail.com
Fri May 12 18:45:04 CEST 2006


...

[Raymond Hettinger]
>> I write:
>>
>>   if n&1:
>>      handle_odd()
>>   else:
>>      handle_even()
>>
>> IMO, functions like is_even() and is_odd() are clutter.  Also, the
>> performance of &1 is unlikely to be matched function calls.

[Fredrik Johansson]
> In your example, the problem is that same thing has to be stated
> twice,

What did he state twice?  I see him checking the parity just once there.

> so the gain from expressing it differently in different places
> is an artificial one.

Sorry, I'm lost.

> More concretely, I can't recall ever seeing an explicit reference to
> "handle_odd" directly after an n&1 test. The information is usually
> contained entirely in the if-clause.

And more lost ;-)

I do the same kind of thing all the time; e.g., here from the tail end
of a hybrid modular/binary gcd function, which uses parity checks in
three places:

    # invariants:
    # a > b >= 0
    # a is odd
    # b is odd or 0
    while b:
        a %= b
        if a & 1:
            a = b-a
        assert a & 1 == 0
        a >>= 1
        if a:
            while a & 1 == 0:
                a >>= 1
        a, b = b, a

    return a << nbits

For a long time CPython took time proportional to the number of bits
in n to compute n&1, so it wasn't actually efficient, but recent
releases repaired that.  In any case the code is quite clear and
directly to the point.


More information about the Python-3000 mailing list