Hacker News new | past | comments | ask | show | jobs | submit login

Okay... I have another one.

In Python:

  >>> -1 % 3
  2
In Javascript:

  >>> -1 % 3
  -1



That is actually an error in the python implementation. According to the language reference: "(a/b)*b + (a%b) = a" where the (a/b) step is rounded towards 0. This implies the if a is negative, (a%b) should also be negative. Note that this modulus standard is also used for the C, C++, and JAVA standard. Here, its python's mess up.


This implies the if a is negative, (a%b) should also be negative.

No, python is giving you the Modulus after division (i.e. a "distance" which should be positive). If you interpret it that way everything is fine:

  >>> a = -1
  >>> b = 3
  >>> (a/b)*b
  -3
  >>> (a%b)
  2
  >>> (a/b)*b + (a%b)
  -1
Perhaps you're thinking of the Remainder?

Edit: it seems there isn't much consensus about what to do when a or b are negative. Wikipedia gives a helpful chart here how different languages choose to implement this: http://en.wikipedia.org/wiki/Modulo_operation


True. I checked the python reference again and it re-adjusts the modulo to have the same sign as the 2nd operand.

>>> 1 % -3 -2 >>> -1 % -3 -1




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: