1

I just got started with Python PCEP course material on netacad.com.

I've come across the following exercises:

   2 % -4 = -2
   2 % 4 = 2

As I understand it, the modulo operator returns the remainder of a division. So 2 divided by (-4) gives (-0.5). How does Python3 calculate the remainder of that as 2?

I know it's stupid but what's the reasoning behind that result?

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503

1 Answers1

0

Briefly, if $a$ is an integer and $b>0$ is a positive integers then you can find an integer $m$ and an integer $r \in \{0,\ldots,b-1\}$ such that $$ a = mb + r. $$ We say that $m$ is the quotient and $r$ is the remainder. For example, if $a=2$ and $b=4$ then $m=0$ and $r=2$.

When $b$ is allowed to be negative, the exact meaning is language-specific. You can work out the case of python by trying a few examples.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503