1
$\begingroup$

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?

$\endgroup$
1

1 Answer 1

0
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.