Integer division, surprising results

Tim Peters tim.one at comcast.net
Wed May 12 17:22:35 EDT 2004


[Tim, on Python's floor division]
>> It's primarily driven by the desire that i%j have the same sign as j.

[Ralf Muschall]
> That's the side effect, not the desire (AFAIK).

In Python, it was deliberate:  Guido and I agreed on this behavior before
Python's first public release, and it was indeed primarily driven by the
desire to have i%j >= 0 whenever j > 0.  Other languages have their own
reasons.  For example, C99 mandates "the wrong" behavior here (where C89 was
silent), and for no reason other than "because that's what Fortran did".

...
> [1] I don't know whether it also offers a shortcut for
> sign(x)*mod(abs(x),y) for people who insist on the bad result.

Python's math.fmod() behaves like the platform C fmod() function.  There's
special value in that when dealing with floating point inputs, because it's
impossible for fmod() to be exact in all cases unless the result has the
same sign as the first argument.  For example, fmod(-1, 1e300) == -1.  If
the result had to have the same sign as the second argument, then the true
result is the unrepresentable (as a 754 double) 1e300 - 1.  Python's %
operator applied to integers makes a lot of sense, but not-- alas --when
applied to floats.






More information about the Python-list mailing list