views:

161

answers:

4

Hi, everyone

I've found some strange behaviour in python regarding negative numbers:

>>> a = -5
>>> a % 4
3

Could anyone explain what's going on?

+9  A: 
KennyTM
@KennyTM: Shouldn't that be (-2 * 4 + 3) ?
Vatine
@Vatine: Fixed thanks. (Was thinking about 5 ^^)
KennyTM
+8  A: 

Here's an explanation from Guido van Rossum:

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

Essentially, it's so that a/b = q with remainder r preserves the relationships b*q + r = a and 0 <= r < b.

Iceman
+1  A: 

Modulo, equivalence classes for 4:

  • 0: 0, 4, 8, 12... and -4, -8, -12...
  • 1: 1, 5, 9, 13... and -3, -7, -11...
  • 2: 2, 6, 10... and -2, -6, -10...
  • 3: 3, 7, 11... and -1, -5, -9...

Here's a link to modulo's behavior with negative numbers. (Yes, I googled it)

wheaties
@NullUserException - yup, it was. fixed. Thanks.
wheaties
A: 

There is no one best way to handle integer division and mods with negative numbers. It would be nice if a/b was the same magnitude and opposite sign of (-a)/b. It would be nice if a % b was indeed a modulo b. Since we really want a == (a/b)*b + a%b, the first two are incompatible.

Which one to keep is a difficult question, and there are arguments for both sides. C and C++ round integer division towards zero (so a/b == -((-a)/b)), and apparently Python doesn't.

David Thornley