3
  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.

Justin Wong
  • 1,455
  • 3
  • 18
  • 25
  • 2
    About question 1. - [`timeit`](http://docs.python.org/py3k/library/timeit.html) is really not difficult to use. – Björn Pollex Mar 29 '11 at 08:28
  • Thanks, I'm just starting out with Python, didn't know there was such a function. Seems like / is a teeny weeny bit faster than //. – Justin Wong Mar 29 '11 at 08:42
  • 1
    For the first question, see the enlightening first answer to [this](http://stackoverflow.com/questions/1396564/why-is-subtraction-faster-than-addition-in-python) question for why this is unlikely to matter much. Specifically: `The speed of the native addition and subtraction opcodes is irrelevant. It's in the noise floor, completely dwarfed by the bytecode evaluation. That's talking about one or two native instructions around thousands.` – Lauritz V. Thaulow Mar 29 '11 at 08:54

1 Answers1

3
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.

Erik Youngren
  • 783
  • 1
  • 6
  • 15
  • Thanks, I knew something like this would work, was simply wondering if there were such a native language feature in Python so I can use an infix operator instead of a function. – Justin Wong Mar 29 '11 at 08:52