p:paragraph –>

As a programmer, you will be quite familiar with the abs function. I thought I was. In fact it was filed in my brain drawer with the absolute mathematical function. It takes a number and provides an always positive or zero result. Right?

Well, mostly. This morning, while typing in the scala REPL:

scala> Math.abs(Int.MinValue)
res0: Int = -2147483648

What? Well, it makes sense at bit-level. Using two-complements representation for signed integers, 0 is considered positive so the negative values have an additional item located at the bottom. Once the size of the integer is fixed there is no way to represent the negation of the lowest integer in the range.

Apparently Scala documentation ignores this corner case, stating that abs always is greater than or equal to zero.

What about the other side of the Languages Pool?

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main()
    int x = INT_MIN;
    int absX = abs( x );
    printf( "%d
", absX );

Guess what… All in the same boat. This code prints INT_MIN which is pretty negative by my standards. Talking about standards, differently from what happens in the Scala world, ISO C specifications state that abs() triggers an undefined behavior in this case.

This is another pitfall when trying to make practical stuff representing abstract concepts. Some pitfalls are quite easy to spot – computer integers are not infinite as the natural numbers are; others are more subtle – computer floating point numbers are not Reals (and not even Rationals).

Lesson learned – know your tools and keep in mind that in theory, theory and practice are the same. In practice, they are not.

2 thoughts on “Absolutely

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.