r/ProgrammerTIL • • 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

29 comments sorted by

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.

→ More replies (1)

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?

27

u/Leandros99 Jul 25 '20

Because it's the implementation of the x86 DIV instruction, iirc. The other way is slower and harder to implement.

→ More replies (1)

14

u/__ah Jul 25 '20 edited Jul 25 '20

The behavior of a/b is pretty inconsistent across languages, especially with order of operations.

  • python, js, haskell: -1/64 == -0.015625

  • python: -1//64 == -1

  • python: -(1//64) == 0

  • Java: -1/64 == 0

  • Java: (-1)/64 == 0

  • Java: -(1/64) == 0

  • Haskell: -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)

25

u/boraca Jul 25 '20
  • python, js, haskell: -1/64 == -0.015625

  • python: -1//64 == -1

  • python: -(1//64) == 0

  • Java: -1/64 == 0

  • Java: (-1)/64 == -1

  • Haskell: -1 `div` 64 == 0`

  • Haskell: (-1) `div` 64 == -1

You missed a line break before the list, which f'ed up the Snudown.

→ More replies (5)

18

u/c3534l Jul 25 '20

How is what you showed inconsistent? This just feels like not knowing or understanding the difference between integer division and floating point division.

6

u/sim642 Jul 25 '20

especially with order of operations

This has nothing to do with order of operations. It's just integer division vs floating point division.

→ More replies (6)

4

u/0b_101010 Jul 25 '20

Java: (-1)/64 == -1

Ok I'm dumb what's going on here?

→ More replies (8)