Why Not Float All the Time?

What’s the point of using integers when you could simply code programs using floating-point values all the time to always get the best results? The reason is a good one, but it takes some explaining.

The answer has to deal with storage and processing power. Integers take less processing power to manipulate. Floating point values take more processing power. But just as you could use a screwdriver to pound in a nail, it’s always best to use the proper tool for the job.

As an example, consider an int and a float variable. According to the sizeof operator, on my computer both variable types occupy four bytes of storage.

The four bytes of storage are just that as far as the computer is concerned. It’s how the bytes are read that’s important. Consider these declarations:

int i = 486;
float f = 123.45;

The value stored in variable i is 486. Its binary representation is:

0000-0000 0000-0000 0000-0001 1110-0110 or 0x1e6

(I’ve added the dashes and spaces above to make the four bytes readable.) That’s straightforward: Binary 111100110 is hex 0x1e6, which is decimal value 486. Maybe not obvious to you, but easy for a computer.

The value stored in variable f is 123.45. Its binary representation is:

0110-0110 1110-0110 1111-0110 0100-0010 or 0x66e6f642

If the hex value 0x66e6f642 is read as decimal, it shows up as 1,726,412,354. (I added commas for readability.) That’s nowhere near 123.45, so the processor is doing some kind of sorcery to extrapolate the proper floating point value.

(Just because you’re curious, I had to use a debugger to view the binary representation of floating-point value 123.45.)

The integer value 486, on the other hand, is read and digested in one gulp. It’s easy for the processor to deal with int values because, in a way, integers are its native tongue. Floating point values require translation. Back in the old days, that duty was handled by a separate math co-processor. Today, the math processor is integrated into the main CPU, but it’s still used to efficiently deal with non-integer values.

So while you could code all the variables in your program as floating point, you’re just adding more overhead. With today’s fast processors you probably won’t see much speed impact, but the point is why add overhead when you don’t have to? Instead, code integer values as ints and use floating-point variables only when necessary.

Leave a Reply