[Python-Dev] Floor division

Tim Peters tim.peters at gmail.com
Tue Jan 23 10:52:51 CET 2007


[Anders J. Munch]
> What design error?  float.__mod__ works perfectly.
>
> >>> -1 % 50
> 49
> >>> -1.0 % 50.0
> 49.0
> >>>

Please read the whole thread.  Maybe you did, but you said nothing
here that indicated you had.  The issues aren't about tiny integers
that happen to be in float format, where the result is exactly
representable as a float too.  Those don't create problems for any
definition of mod.  But even non-tiny exact integers can.

> It's only Decimal.__mod__ that's inconsistent.  float.__mod__ has the
> usual floating-point inaccuracies, but then with float that goes with
> the territory.

No.  Decimal.__mod_  always returns the mathematically exact result.
It has this in common with math.fmod() (in fact, math.fmod() and
Decimal.__mod__() have the same definition, ignoring IEEE endcases).
It's impossible to do so under Python's integer-derived mod
definition.  Read the whole thread for why -- we can't even guarantee
that abs(a%b) < abs(b) for non-zero finite floats under the current
mod, and that has in fact been a source of complaints over the years.
math.fmod and Decimal.__mod__ do guarantee abs(a%b) < abs(b) for all
non-zero finite floats, and moreover guarantee that a%b is an exact
integer multiple of `b` away from `a` (although that integer may not
be representable as a float) -- again it's impossible for the a -
floor(a/b)*b definition to do so for floats.

> I've had occasion to use it, and it was a pleasant surprise that it
> "just worked", so I didn't have to go to the math module and ponder
> over the difference between modulo or remainder.

There's no such distinction in Python's math module -- fmod is the
only modular reduction function in the math module.  The `decimal`
module has two such functions (see earlier messages in this thread for
examples -- neither matches Python's mod function).


More information about the Python-Dev mailing list