[Python-Dev] PEP 238 - The // operator should truncate instead of floor

Fredrik Johansson fredrik.johansson at gmail.com
Wed Aug 29 18:23:40 CEST 2007

On 8/29/07, dany <danzat at gmail.com> wrote:
> Looking deeper in the python PEPs, I saw that division on integers is
> defined as: idiv(a, b) = floor(fdiv(a, b)).
> This non-quotient division leads to some odd results, e.g. Python seems
> to think -3/2+3/2 = -1. This is clearly, and correct me if I'm mistaken
> - wrong.

Rounding integer division can't be defined such that fractional
information is preserved. For example, the sum 1/2 + 1/2 (with
rounding division), doesn't equal 1 whether the rounding is done up or
down. Python's choice to round to the floor of the exact quotient is
entirely in order, and in fact, I've found it very useful in some of
my code.

There is an easy fix for your problem: write a custom division function, e.g.

def div(a, b):
    if a*b > 0:
        return a // b
        return -(abs(a)//abs(b))

Either that, or use any of the modules for rational arithmetic
available for Python.


More information about the Python-Dev mailing list