Floating Point Mystery(not really)

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.

2 Responses to “Floating Point Mystery(not really)”

  1. Amy Says:

    Wow…this just goes to show me that I am completely clueless about the programming world. It also reminds me how impressed I am with my fiancee’s gifts…we certainly have our individual talents, and for this I am thankful. It keeps life interesting!

  2. alex Says:

    2.4/0.2 yields something like this: 11.999999999999998
    int(x) then really just truncates rather than rounds and returns whatever’s on the left of the decimal point.

Leave a Reply

You must be logged in to post a comment.