3 ms·
In a quite similar example of a bad convention, I find it extremely frustrating that many programming languages do not have a modulus operator (%) which behaves
by jacobolus 15y ago
In a quite similar example of a bad convention, I find it extremely frustrating that many programming languages do not have a modulus operator (%) which behaves as modulo in mathematics. To be explicit, there are multiple choices of the sign of:
x % y
When either x or y is negative, or both (the full details are described at Wikipedia: http://en.wikipedia.org/wiki/Modulo_operation http://en.wikipedia.org/wiki/Modulo_operation). In common mathematical notation x mod y, the result always shares the sign of the divisor y. For example,
–14 mod 10 = 6
6 mod –10 = –4
The same is the case in python:
>>> -14 % 10
6
>>> 6 % -10
-4
Unfortunately, in JavaScript (and various other languages), a different convention is chosen. The result instead shares the sign of the dividend:
> -14 % 10
-4
> 6 % -10
6
This is really annoying because we quite frequently want to use the modulus operator to do things like normalize an angle to the range [0, 360°). To perform this normalization on an angle a in JavaScript, if a < 0, requires a computation like:
a_prime = a % 360 + 360
I end up usually defining a function like:
var mod = function (x, y) {
var js_mod;
return (js_mod = x % y) && (x > 0 ^ y > 0) ? js_mod + y : js_mod;
}
- ScottBurson 15y agoAgreed. A closely related infelicity is that integer division in most languages (and indeed, on most CPUs that have an integer divide instruction) truncates toward zero. So 1 / 2 and -1 / 2 both evaluate to zero. The `floor' operation -- that truncates toward negative infinity -- is a more useful primitive, and goes hand in hand with the modulo operation defined as you describe.
- chalst 15y agoRight. A convenient property to have that is held by the Python version is (for nonzero n) x==n*floor(x/n)+x%n This property isn't held by the Javascript variant, where there is a somewhat more complex property x==n*sign(x/n)*floor(abs(x/n))+x%n
- jacobolus 15y agoIn python, math.floor(x / n) can be written x // n, so: x == n * (x // n) + x % n
- qntm 15y agoThe worst part is, if you are a mathematician and you expect the modulus operator to behave exactly as it does in mathematics then it can be maddeningly difficult to track down why your program isn't working correctly. You just don't expect simple mathematical operators to start malfunctioning.
- lelele 15y agoCommon Lisp, of course, gets modulus right: (mod -1 5) => 4 (mod 13 4) => 1 (mod -13 4) => 3 (mod 13 -4) => -3