by seivadmas · 11y ago · 0 comments
x = 1987654321 and y = -1987654321? Then the difference between them is -319658654 (negative) which proves that x is less than y. That’s less than correct.
Which is completely 100% wrong. Surely the difference would be x - y i.e (1987654321 - (-1987654321)) = (1987654321 + 1987654321) = 3975308642.Which is perfectly ok, because that's positive and so proves x is greater than y. So this comparison works just fine for negative integers...
Overflow makes intuitive arithmetic do unusual things.
Similarly, using a+b/2 for binary search midpoints is wrong. http://googleresearch.blogspot.com/2006/06/extra-extra-read-...
The previous commenter may have entered that into say, a Python console where it wouldn't exhibit that behavior.
For many data types, like time, that will normally never happen, making subtraction the safest no-brainpower-needed approach. If in doubt, use the next larger integer type.
I actually like and use C everyday, but it would be aberrant for me to say essentially what the article implies: "A math algorithm is wrong because it doesn't work in C"