Alex Rivera | Logout

Modulo for negative dividends in Python

Asked 2012-04-08T14:28:26.750
10

Been looking through other answers and I still don't understand the modulo for negative numbers in python

For example the answer by df

x == (x/y)*y + (x%y)

so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3

Doesn't this (-2 - (-2/5)*5) =0 or am I just crazy? Modulus operation with negatives values - weird thing?

Same with this negative numbers modulo in python Where did he get -2 from?

Lastly if the sign is dependent on the dividend why don't negative dividends have the same output as their positive counterparts?

For instance the output of

print([8%5,-8%5,4%5,-4%5])

is

[3, 2, 4, 1]
Edit
Report

1 Answer

0

When you divide ints (-2/5)*5 does not evaluate to -2, as it would in the algebra you're used to. Try breaking it down into two steps, first evaluating the part in the parentheses.

  1. (-2/5) * 5 = (-1) * 5
  2. (-1) * 5 = -5

The reason for step 1 is that you're doing int division, which in python 2.x returns the equivalent of the float division result rounded down to the nearest integer.

In python 3 and higher, 2/5 will return a float, see PEP 238.

answered 2012-04-08T14:38:46.807

Your Answer