msg289647 - (view) |
Author: Marcos Thomaz (marcosthomazs) |
Date: 2017-03-15 07:56 |
At divide a negative integer number for a positive integer number, the result is wrong. For example, in operation: a, b, c = -7, 2, 7 d = divmod(a, b) print a//b, a%b, c[0], c // b, c%b The values printed are -4 1 3 1 |
|
|
msg289648 - (view) |
Author: Martin Panter (martin.panter) *  |
Date: 2017-03-15 08:16 |
If you ignore the c[0] argument, the rest looks fine to me. See the documentation at <https://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations> and <https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex>. The double-slash operator is called “floor division”. If you are expecting some other rounding, see <https://docs.python.org/2/faq/programming.html#why-does-22-10-return-3>. |
|
|
msg289655 - (view) |
Author: Marcos Thomaz (marcosthomazs) |
Date: 2017-03-15 09:39 |
I'm sorry, but was a typing error. Try this operations: a, b, c = 7, -7, 2 print "1:", a // c, a % c print "2:", b // c, b % c the result is: 1: 3 1 2: -4 1 The division is the same, except by the signal (variable b is negative, but both, variables "a" and "b" are integers). |
|
|
msg289656 - (view) |
Author: Marcos Thomaz (marcosthomazs) |
Date: 2017-03-15 09:47 |
Try this operations, in interactive environment: >> 7 // 2 3 >> -7 // 2 -4 |
|
|
msg289659 - (view) |
Author: Marcos Thomaz (marcosthomazs) |
Date: 2017-03-15 09:55 |
Note that mathematic expression is wrong. -7 divided by 2 is -3, not -4 |
|
|
msg289665 - (view) |
Author: Eryk Sun (eryksun) *  |
Date: 2017-03-15 10:39 |
> -7 divided by 2 is -3, not -4 Integer division in Python is floor division, and it's self-consistent with the implementation of the modulo operation such that the following identity is satisfied: (a % n) == a - n * (a // n). For example: (-7 % 2) == -7 - 2 * (-7 // 2) 1 == -7 - 2 * (-4) == -7 + 8 This behavior is consistent with mathematical analysis languages such as MATLAB, Mathematica, Mathcad, and R. It's also consistent with Ruby, Perl, and Tcl. However, it's different from C, C++, C#, Java, PHP and many other languages. See the following Wikipedia article: https://en.wikipedia.org/wiki/Modulo_operation Please do not change the status and resolution of this issue again. This is not a bug. |
|
|