Math.abs Returns a Negative Number
Consider this a public service announcement: your code could very well be broken.
Ben Maurer has an article about
edge cases in C#’s Math.abs. However, it’s not merely some
weird C# thing.
The trouble is this: the range of signed twos-compliment integers (read: most integer types in nearly all languages) are larger on the negative than the positive side. For example, a signed 16-bit integer ranges from -32,768 to 32,767, just as a a signed 32-bit integer ranges from -2,147,483,648 to 2,147,483,647.
The practical upshot? Within the range of every particular fixed-precision
integer type there is a negative number which has no positive equivalent.
For such numbers, integer abs() and even negation are essentially
undefined.
This has been the source of a lot of bugs.
If you’re writing in Ruby or another language with automatic Bignums, you’re okay (but watch those C extensions…). Everyone else? Check your code!
Incidentally, while you’re checking your code, here are two previous “public service” articles, drawing attention to two other widespread bugs:
P.S.: code written in Ruby is also immune to the binary search bug, again because of automatic integer embiggening. At this point, I think designing a new scripting language without a builtin bignum type and automatic promotion would be simply irresponsible.