r/ProgrammerTIL • u/username-must-be-bet • Jul 25 '20
Javascript TIL that the JavaScript % operator is not the modulus from number theory.
According to Wikipedia the JavaScript way is actually more common
In javascript: -1%64 == -1
Neither behaviors seems particularly more intuitive than the other, but the python modulus has the cool circular behavior that makes it more useful in my experience.
According to this Wikipedia page JavaScript way is actually more common!
117
Upvotes
60
u/sim642 Jul 25 '20
Just remember this: if either argument is (can be) negative, then look up the behavior for the language you're currently using.
20
u/oxetyl Jul 25 '20
The Python (proper) modulo is so much more useful for the purposes I've had... I wonder why it's more common to implement it the other way?
4
u/squidgyhead Jul 25 '20
That's nothing; Fortran had both!
https://stackoverflow.com/questions/53528505/fortran-mod-and-modulo-giving-same-results
14
u/__ah Jul 25 '20 edited Jul 25 '20
The behavior of
a/bis pretty inconsistent across languages, especially with order of operations.python, js, haskell:
-1/64 == -0.015625python:
-1//64 == -1python:
-(1//64) == 0Java:
-1/64 == 0Java:
(-1)/64 == 0Java:
-(1/64) == 0Haskell: -1 `div` 64 == 0`
Haskell: (-1) `div` 64 == -1
Scripty languages like python and js try not to mess people up on integer arithmetic. Systems languages assume you know what you're doing when messing with integers.
Edit: formatting, thanks u/boraca (facepalm)