Modulo operator python

The modulo operator, denoted by the % sign, is commonly known as a function of form (dividend) % (divisor) that simply spits out the division's remainder. When both the dividend and divisor are positive integers, the result is simply the positive remainder. For instance, 5 % 3 = 2, and 7 % 3 = 1. But how would you explain why -7 % 3 = 2 in Python? It's actually pretty simple.
The % operator in Python yields integers with the same sign as the divisor. Take a look at the visualization below. The dividend is in red, and the divisor is in blue.
Think of it as if you're filling up a basket with bricks. The basket's depth is the dividend; each brick's length is the divisor's magnitude. In the case above, the red basket's depth is -7 (opens to the right by starting from -7), and the length of each blue brick is 3. Knowing that the remainder must be positive since 3 is positive, fill up the basket until it overflows to the positive side of the number line. When the last brick is attached, two units overflow, yielding 2 as the correct answer.
Next, the diagram below shows a case where the divisor is negative and the dividend is positive. The basket opens to the left because its depth is now positive 7. Remember, the resultant "remainder" here must have the same negative sign as -3. How can that happen? It means the basket should overflow into the negative side of the number line, in this case two units. Thus -2 is the answer.
What if both the dividend and divisor are negative integers? Notice how the same rule applies: negative three yields negative one. In order to maintain the same sign, fill up the basket only until the negative sign doesn't change, i.e. the basket shouldn't overflow (a one-unit shortfall in this example).
Realistically, if the integers involved in the modulo operation get significantly larger in magnitude, we won't be able to draw out these "divisor bricks". Regardless, just knowing these two rules will yield correct outputs:
  • Resultant remainders have same signs as divisors.
  • Don't just alter the remainder's sign, i.e. divide and fill up until the bricks cause an overflow or shortfall to the correct sign's side.
One last example: 176 % -14 = ? Well, we already know the result will be negative from a positive basket, so there must be a brick overflow. 176 / 14 ≈ 12.6 and 14 * 13 = 182, so the answer is 176 - 182 = -6. A six-unit overflow to the negative side.

Comments

Popular posts from this blog

Python Programming

how to free port 80 in windows

Adding a New Protocol IN NS2 (NETWORK SIMULATOR)