Archive for the 'Programming' Category

Floating Point Mystery(not really)

Tuesday, July 25th, 2006

I’m currently slugging my way through “Mastering Algorithms with Perl”, which is an excellent read for any lover of Perl, and I stumbled across some interesting factos. Take the following example:

#—-Example Begin—#
#!/usr/bin/perl

$answer = 2.4/0.2;

print $answer,”\n”;
print int($answer);

#—-Example End—#

Executing the above script will print the following:

12
11

Line one is what we expected, because 2.4 divided by 0.2 is 12, and 12 is technically the integer of 12. But wait a minute, there’s something wrong with line 2. So what devil is going on here? News to me, but apparently, with floating points, and this is with most programming languages, the floating point has a binary representation. What is really happening is the binary representation is being divided, which when converted back is less than 12. The int function in perl always rounds towards 0, hence 11.

More information in regard to the confusing world of floating points and computers, click here.