V
V
vohman2018-03-08 08:22:25
Python
vohman, 2018-03-08 08:22:25

How do the // and % operators work in Python for negative numbers?

I expected the obvious result for the expressions 10//3 and 10%3 : I got 3 and 1 respectively.
But when I did the same for negative 10, I got an unexpectedly "weird" result:
- 10//3 == - 4
- 10%3 == 2
Trying divmod(10, 3) and divmod(-10, 3) got that the same result, which is natural.
It turns out that the result of the work of integer division and modulo division operators in Python for negative numbers does not obey the classical mathematical laws at all, but is calculated according to some kind of its own dependency function.
Indeed, in mathematics 10//3 and -10//3 will only differ in sign (3 and -3).
help(divmod) explains that the result of divmod(x, y) is div*y + mod == x.
I would like to understand how in Python you can quickly understand (calculate in your mind) the result of the operation x//y and x%y with negative values ​​(it is easy and familiar for positive ones)?
And what justifies such dependence in Python for these operations, and not the "classical" mathematical one?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AVKor, 2018-03-08
@AVKor

And what justifies such dependence in Python for these operations, and not the "classical" mathematical one?

Everything is exactly the same as in mathematics. You just don't know her.

V
vohman, 2018-03-08
@vohman

Of course, I'm not a certified mathematician :)) as they wrote to me, but I can still master school mathematics))
Regarding rounding and in which direction - this is not in the concept of integer division in mathematics, and it seems like in Python for non-negative numbers no such rounding is done.
In addition, -10/3 = -3.33333333.... and rounding (since I am offered to use it) will be towards -3 - this is in mathematics. And that's how it's done in other languages.
It turns out that in mathematics:
(-10) "integer divided by" (3) is equal to (-4) ?
I always thought that -10 div 3 equals -3 in math.
---------
Let's say I don't know math..
Then in C the result of -10 div 3 is
-3 -1 n = div(-10.3); printf("Quotient and remainder: %d %d\n", n.quot, n.rem); return 0; } On old Pascal, the result of -10 integer divided by 3 will be the same (-3) var result : integer; begin result := -10 div 3; writeln('Result = ', result); end. Why is the result ( -4 ) in Python? - no, it is clear that he is considered according to his own law. But how can I quickly calculate it in my head according to the formula that I indicated above?
And on what basis is this division considered in Python like this and not "as usual"?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question