Modul (%) in python not like in C?
Bryan Olson
fakeaddress at nowhere.org
Mon Sep 10 12:09:34 CEST 2007
Dennis Lee Bieber wrote:
> The best answer is probably to be found from the definition of
> divmod()
The divmod() function is one of those little delights that reminds
me why I love Python, but I do not think it answers the question
here. The definition of divmod() references the '%' operation, and
not the other way around.
http://docs.python.org/lib/built-in-funcs.html
http://docs.python.org/ref/binary.html
>>>> divmod(70, 6)
> (11, 4)
>>>> 6*11 + 4
> 70
>>>> divmod(-70, 6)
> (-12, 2)
>>>> 6 * -12 + 2
> -70
Also:
>>> divmod(70, -6)
(-12, -2)
>>> -6*-12 + -2
70
>>> divmod(-70, -6)
(11, -4)
>>> -6*11 + -4
-70
> Or in general terms
>
> (a, b) = divmod(x, y)
> x = y * a + b
> IOWs, the definition of modulo, and the definition of integer division,
> are linked...
Right. Thus given integers x and y, y!=0, Python and C agree:
x == (y * (x / y)) + (x % y)
The disagreement is how integer division rounds. In C, integer
division rounds toward zero. In Python, integer division rounds
downward.
--
--Bryan
More information about the Python-list
mailing list