7 ms·
In what languages is n % 2 -1 for negative odd numbers? Edit: apparently JS, java, and C all do this. That’s horrifying
by notfish 2y ago
In what languages is n % 2 -1 for negative odd numbers?
Edit: apparently JS, java, and C all do this. That’s horrifying
- jagged-chisel 2y agoHorrifying? It’s mathematically correct.
- michael1999 2y agoIt's actually really awkward. Math usually considers (-7 mod 5) === (2 mod 5). But in C, (-7 % 5 != 2 % 5).
- arcastroe 2y agoNo. Math considers -7 = 3 modulo 5. it's a ring that repeats every 5 units. -7 + 5 + 5 = 3. Think of a clock which is a ring of size 12. In a clock, going backwards 15 hours (-15) is the same as going backwards 3 hours (-3) which is the same as going forwards 9 hours. -15 = -3 = 9 modulo 12
- michael1999 2y agoYou are correct. I thinko'd and missed the edit window. I meant to say: Math usually considers (-7 mod 5) === (3 mod 5). But in C, (-7 % 5 != 3 % 5). The issue is that -7 and 3 are congruent, but the % operator keeps the sign. So -7 % 5 yields -2, not +3. Those are congruent, but not equal. I've never had a use for this behaviour, but I've definitely had to work around it. The lazy way is ((x % n) + n) % n which is safe (assuming n > 0).
- arcastroe 2y ago+1. I wholeheartedly agree. That "lazy way" looks all too familiar haha.
- affinepplan 2y agowrong. it's not any more correct than 1. that's the key part of an "equivalence" class is that the elements are "equivalent"
- seritools 2y agoit's a semantics problem, not a maths problem - modulus and remainder are not the same operation. This easily trips up people since `%` is often called "modulo", yet is implemented as remainder operation in many languages https://stackoverflow.com/questions/13683563/whats-the-difference-between-mod-and-remainder https://stackoverflow.com/questions/13683563/whats-the-diffe...