Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncated versus floored division in Python

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?

like image 777
rwallace Avatar asked Mar 26 '13 09:03

rwallace


People also ask

What is the difference between division and floor division in Python?

/ vs // — division vs floor divisionThe result of regular division is always a float, whereas if one of the operands is a float in floor division, then the output will be a float.

What is truncation division in Python?

The truncating division operator (also known as floor division) truncates the result to an integer and works with both integers and floating-point numbers. As of this writing, the true division operator (/) also truncates the result to an integer if the operands are integers. Therefore, 7/4 is 1, not 1.75.

What are the two types of division in Python?

In Python, there are two kinds of division: integer division and float division.

What is the difference between floor division and division?

Floor division is a normal division operation except that it returns the largest possible integer. This integer is either less than or equal to the normal division result.


1 Answers

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 += 1
    return q

>>> trunc_div(1,-2)
0
>>> trunc_div(999999999999999999999999999999999999999999, -2)
-499999999999999999999999999999999999999999L
>>> trunc_div(999999999999999999999999999999999999999999, 2)
499999999999999999999999999999999999999999L
>>> trunc_div(1,2)
0
>>> 
like image 133
Abhijit Avatar answered Oct 09 '22 07:10

Abhijit