OTOH, the largest "wat" of C-like languages is the following:
> -8 % 5
-3
whyPython here is once again correct:
>>> -8 % 5
2You may as well use {white, blue, black, red, green} to represent congruences mod 5, mathematically speaking it's not wrong, as long as they respect the axioms of a field.
What's "wat" (in the same sense as the js "wat" talk) is that the answer changes if the argument becomes negative. By all reasonable definitions of modular arithmetic, -8 and 7 are in the same class mod 5. Why is then:
> (-8 % 5) == (7 % 5)
false
in C-like languages? I'm pretty sure it's perfectly consistent with all the relevant language standards, but it's a "wat" nonetheless.It's the same in Python though? you just prefer the way it behaves (though to be fair it's generally more useful and less troublesome): Python's remainder follows the sign of the divisor (because it uses floored division), while C's follows the sign of the dividend (because it uses truncated division).
Strictly speaking, neither is an euclidian modulo.
Haskell does it right. Instead of having operators like %, it gives the programmer choice to choose either the modulus or the remainder. Using GP's example:
ghci> 2 `div` (-5)
-1
ghci> 2 `mod` (-5)
-3
ghci> 2 `quot` (-5)
0
ghci> 2 `rem` (-5)
2
And we have both (x `quot` y)*y + (x `rem` y) == x and (x `div` y)*y + (x `mod` y) == x