3 ms·
Moving past the intuition for how division and remainders work for real numbers, there are other ways to look at "obvious" answers that suggests -7/2=4. Consid
by Laremere 5y ago
Moving past the intuition for how division and remainders work for real numbers, there are other ways to look at "obvious" answers that suggests -7/2=4.
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.
- superjan 5y agoIt is not so much my intuition but the intuition of the language designers. I would prefer euclidian division personally.
- strenholme 5y agoTrue, but both Python’s “int()” operation and the C99 and C11 standard for division operators truncate towards 0. [1] [1] e.g. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf PDF page 94/physical page 82
- housecarpenter 5y agoPython's int() truncates towards 0, but (at least in Python 3, I don't know if it was always the same in older versions) its division operator always floors, so -7 // 2 gives -4 even though int(-3.5) is 3. (The int() function is best thought of as just "make this float into an integer, I don't really care how"; if you want to be more specific, you have math.floor(), math.ceil() and math.trunc(), and you also have round(), which rounds towards the closest integer; if the float is evenly between the two integers, it goes towards 0 when the integer part is even and away from 0 when the integer part is odd.)