Integer division, surprising results

Tim Peters tim.one at comcast.net
Mon May 10 10:43:04 EDT 2004


[Michael Cornelius]
> As an old C programmer, I'm surprised by some results I'm getting with
> integer division. For example:
>
> >>> -1/1000
> -1

As an old C programmer, you should have known that the C standard (C89)
didn't define whether the result here was -1 or 0.

> >>> -9/2
> -5

Likewise C didn't define whether this was -5 or -4.

> I expect the results of these expressions to be 0 and -4,
> respectively.

Most C compilers do generate code to return those.

> I've looked at faqs and documentation, and nothing jumped out at me.
> Can anyone explain the reasoning for this?

It's primarily driven by the desire that i%j have the same sign as j.  If
you want that, and also want

    i == (i/j)*j + (i%j)

then integer division has to return the floor.  C also requres that identity
to hold, and then compilers that truncate i/j need to make i%j have the same
sign as i.

There are few real use cases for i%j when j is negative.  When j is
positive, there are many, and in virually all of them it's more useful for
i%j to be >= 0 (if the clock says 10 now, what did it say 200 hours
go?  -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite).





More information about the Python-list mailing list