Integer division and remainder

Tim Peters tim.one at home.com
Wed Aug 15 05:34:51 EDT 2001


[Paul Rubin]
>    7 / 3 =  2
>   -7 / 3 = -3
>
> This is kind of strange.  Normally you expect (-a)/b to be the
> same as -(a/b). That's what happens in most languages, where
> division rounds towards zero:

[Marcin 'Qrczak' Kowalczyk]
> Donald Knuth says that Python is right and C is wrong, and I agree
> with him here. I expect a%b for positive b to return a value in the
> range [0, b).

While I'm sure Marcin knows this, lots of people don't:  the "classic" C
standard explicitly allows either result, so anyone relying on "what
everyone knows" <wink> is playing with fire.  C99 finally made up its mind,
and chose wrongly for compatibility with Fortran (the only reason given in
the C Rationale).

WRT Python, the decision to do flooring integer division was very
deliberate, and not something Guido (or I -- since I pushed him this way,
it's my fault <wink>) has ever had cause to regret.  We simply regret that
division returns an integer at all(!).

missing-the-forest-for-the-ints-ly y'rs  - tim





More information about the Python-list mailing list