It also desirable to have the remainder consistent with the result of division, such that x = d*r + mod, where r is the result of division. Combine that with the above requires negative mods.
It also desirable to have the remainder consistent with the result of division, such that x = d*r + mod, where r is the result of division. Combine that with the above requires negative mods.
Consider x/3=y. For real numbers, it's trivial to manipulate this equation into (x-3)/3=y-1. However, this only works when integer division rounds down.
5/3 = 1 rem 2 or 1 rem 2
4/3 = 1 rem 1 or 1 rem 1
3/3 = 1 rem 0 or 1 rem 0
2/3 = 0 rem 2 or 0 rem 2
1/3 = 0 rem 1 or 0 rem 1
0/3 = 0 rem 0 or 0 rem 0
-1/3 = -1 rem 2 or 0 rem -1
-2/3 = -1 rem 1 or 0 rem -2
-3/3 = -1 rem 0 or -1 rem 0
One of these has a consistent pattern, the other doesn't.All of this is a fairly moot point: The answer is it should do what the algorithm using it needs it to do.
[1] e.g. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf PDF page 94/physical page 82
From PDF page 94 (physical page 82) of the draft C99 standard: [1] The result of the / operator is the quotient from the division of the first operand by the second
This is a little vague; it would be better if they called it the “quotient from Euclidean division” (EDIT: This was incorrect. Actually, it’s the quotient from algebraic division, with the fraction truncated, also called “truncation towards zero”. See discussion below.), which is well defined as being -3 in the above example; see https://en.wikipedia.org/wiki/Euclidean_division (EDIT: Euclidean is -4; truncation towards 0 is -3)
[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
main() { printf("%d\n",-7/2);}
Let’s look at, oh, C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdfPDF page 110, physical page 92: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. with a footnote: This is often called ‘‘truncation toward zero’’
-7/2 is -3.5, so discarding the fractional part gives us -3
In practice, this offloads the problem to your programmer in at least every other case (i.e. when % doesn’t what they need out of box), who then miscalculates or mistests their solution and now the problem is yours.
It doesn’t matter what the standard says, there should be many functions, each for a combination of signs (or roundings) you want in the results. Because your library doesn’t suck and your programmer has things to do instead of fiddling with off by ones and other primitive but highly error-prone-under-stress bs.
-4 also makes sense.
> It also desirable to have the remainder consistent with the result of division, such that x = d*r + mod, where r is the result of division. Combine that with the above requires negative mods.
Python's behaviour is consistent with that definition:
>>> divmod(-7, 2)
(-4, 1)
-7 = -4 * 2 + 1