A quirk of computer numbers and simple arithmetic defeats my digital creatures



Artificial life systems have a reputation for finding all sorts of obscure bugs in your code, no matter how rare or unlikely the conditions to cause the bug are. I’ve got an oddball one. It causes a run time error and shuts down the entire system, and it is an extraordinarily unlikely event, happening once in every 4,294,967,296 possible values. Let me just make sure that bug is what I think it is with a couple of tests.

Now let me deliberately reproduce the problem to be certain I’m right.

The problem is computer numbers have some little quirks that it’s easy to forget about. Most of the time, it doesn’t matter. I’m using 32 bit signed integers. That means, amongst other things, that adding one to the highest number that can be represented turns it into the lowest number that can be represented.

2,147,483,647+1=-2,147,483,148

That quirk has caught me before, so of course I tested for it this time, not wanting to step in the same trap twice, but I still got an error:


Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: -2147483648

And gee whiz golly, but that number looks familiar.

It’s another oddball quirk, related to the above. Multiply any negative number by negative one, and you get a positive number.

-1*1=1
-50244*-1=50244
And
-2,147,483,648*-1=-2,147,483,648

And there it is. The lowest number that can be represented by a 32 bit signed integer multiplied by negative one is the same number. It doesn’t change. It stays the lowest possible number that can be represented by a 32 bit signed integer.

Now I know what the problem is. Let’s see if I can fix it without the code getting too ugly.

Yep, easy fix, and we can now move on with our lives.





Leave a Reply