Take for example C

#include <stdio.h> int main(int argc, char *argv[]) { printf("-28%%3 => %d\n", -28%3); printf("28%%-3 => %d\n", 28%-3); return 0; } -28%3 => -1 28%-3 => 1 

And now python

 from math import remainder print(-28%3, remainder(-28,3)) print(28%-3, remainder(28,-3)) 2 -1.0 -2 1.0 

Why is that? Why does python return 2 for a simple remainder of the division?

  • one
    Because the % operator in python is modulus. And this is not the same as remainder. - Enikeyschik

1 answer 1

The fact is that unlike C, the % operator in Python returns a value with the same sign as the divisor. Those. A step is added that calculates the difference with a negative value.

The calculation is as follows.

-28% 3 = (-9 * 3 - 1)% 3 = -1% 3 = -1

28% -3 = (9 * 3 + 1)% -3 = 1% -3 = 1

In this case, C stops and does not perform further actions, but Python leads the value to the same sign as the divisor.

-28% 3 = (-9 * 3 - 1)% 3 = -1% 3 = -1 + 3 = 2

28% -3 = (9 * 3 + 1)% -3 = 1% -3 = 1 - 3 = -2

Details are described here.