To establish context, I'm talking about integer arithmetic only, on large integers so going via floating point isn't an option, and using negative numbers so the difference between floored and truncated division matters.
When performing division on negative integers, typical hardware and C family programming languages give the truncated result e.g. 1 / -2 = 0. Python 2 gives the floored result e.g. 1 / -2 = -1.
Notwithstanding arguments about which is intrinsically better, is there a way to get Python to give the truncated result? Does it make any difference if you use Python 3 instead of 2?
Ok, if you just want a solution, remember int
truncates the number, so instead of doing integer divison, truncate a float with int
int(1./-2)
If you are using Python 3.X, you can simply do
int(1/2)
If you want the same behavior in Py 2.X import division from future
from __future__ import division
int(1/2)
If you want to know the exact reason for this behavior, read this wonderful article Why Python's Integer Division Floors
Looking at your predicament in using float for division, here is an alternate approach that seems to be working as far as I have tested. Feel free to let me know of any issues you are facing
>>> def trunc_div(a,b):q, r = divmod(a,b)if q < 0 and r:q += 1return q>>> trunc_div(1,-2)
0
>>> trunc_div(999999999999999999999999999999999999999999, -2)
-499999999999999999999999999999999999999999L
>>> trunc_div(999999999999999999999999999999999999999999, 2)
499999999999999999999999999999999999999999L
>>> trunc_div(1,2)
0
>>>