Search code examples
pythondivision

Truncating division in Python 3.2


  1. Is integer floor division // faster than float division / in Python 3.2? If I know I'm going to be working with integers only, should I favour // instead of defaulting to /?

  2. How do I get integer truncation behaviour in Python 3.2?

    1/2 = 0

    -1/2 = 0

Thanks.


Solution

  • from math import (floor, ceil)
    def trunc_div(a, b):
        c = a / b
        return floor(c) if c > 0 else ceil(c)
    

    Test it to make sure it's right. It's late and I'm doing math while sleepy.

    Actually, don't do that. While seeing if I could subclass int to do truncated division (don't do that either (also, it didn't work)), it occurred to me that int() itself will truncate reals, resulting in this:

    def trunc_div(a, b):
        return int(a / b)
    

    Which is a rather foolish wrapper.

    So, just use float division, and truncate it with int():

    >>> int(1 / 2)
    0
    >>> int(-1 / 2)
    0
    

    This gets you pretty close to the infix notation you desired.

    The moral of this story is... don't let your friends code while drowsy.