[Python-ideas] division oddness
Terry Reedy
tjreedy at udel.edu
Fri May 7 05:24:50 CEST 2010
On 5/6/2010 9:09 PM, MRAB wrote:
> Mathias Panzenböck wrote:
>> Shouldn't by by mathematical definition -x // y
be the same as -(x // y)?
When defining division of counts, which have no signs, quotient and
remainder cannot be negative. So division both rounds down and rounds
toward zero. It both truncates and floors.
When defining division on integers (signed counts), one can either
define it to round down or to round toward zero, but obviously not both.
As mentioned in the article Chris linked to,
http://en.wikipedia.org/wiki/Modulo_operation
one can also round down or up depending on the sign of the divisor.
The above definition is 'round toward zero' truncation. It has the
anomaly that 0 then is the rounded value (and representative) of all
ratios in the doubly open length-2 range (-1, 1) while all other
quotients represent a half-open length-1 range. The is because -0 == 0
whereas -n != n for all other ints. For 'round down', every quotient,
including 0, represents a half-open length-1 range.
> It's so that:
> y == (y // x) * x + (y % x)
> is always True (assuming x != 0).
No, this is true for any definition of y//x if you *define* y % x to be
y - (y//x)*x. But for truncation, this mean that the sign of y%x depends
on the sign of y rather than the sign of x, as with floor division. The
latter is probably more useful more of the time. For instance, y % 2 has
only 2 possible values (0,1) with flooring rather than three (-1, 0, 1)
as with truncation.
Terry Jan Reedy
More information about the Python-ideas
mailing list