Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!c:/perl/bin/perl $x=100.0; $y=-100.01; print $x+$y;
I am getting output as
-0.0100000000000051
please help me out why this is coming ? how to ensure to get only -0.01

Replies are listed 'Best First'.
Re: can't Understand output
by moritz (Cardinal) on Apr 15, 2008 at 18:45 UTC
    Perl uses your CPU's floating point numbers under the hood which have some inaccuracies.

    You can use bigrat instead, or rely only on integers, or round after a few digits.

Re: can't Understand output
by apl (Monsignor) on Apr 15, 2008 at 18:49 UTC
    Similar questions have been asked two or three times this year. For a good overview, please see When is a 2 not a 2?.
Re: can't Understand output
by FunkyMonk (Bishop) on Apr 15, 2008 at 18:46 UTC
    Generally, computers store numbers with decimal places as floating point numbers, which aren't stored exactly. The Some solutions are

    • work with some multiple of the numbers (eg 100 for yours), so you could use $x = 10000; $y = -10001; print $x - $y;
    • use printf to round your answer, like so printf "%0.2f", $x+$y

Re: can't Understand output
by tachyon-II (Chaplain) on Apr 15, 2008 at 23:52 UTC
Re: can't Understand output
by casiano (Pilgrim) on Apr 16, 2008 at 07:58 UTC
    Yes, IEEE floating point numbers aren't exact representations. Use Math::BigFloat:
    pp2@nereida:~/src/perl/testing$ cat -n addlong.pl 1 use warnings; 2 use strict; 3 use Math::BigFloat ':constant'; 4 5 my $x=100.0; 6 my $y=-100.01; 7 print (($x+$y)."\n");
    And now:
    pp2@nereida:~/src/perl/testing$ perl addlong.pl -0.01
    Best

    Casiano

Re: can't Understand output
by swampyankee (Parson) on Apr 16, 2008 at 18:44 UTC

    Because 0.01 cannot be exactly represented as a finite sum of powers of two, just as 1/3 cannot be exactly represented as the finite sum of powers of ten. Floating point numbers cannot represent all rational, let alone all real, numbers in a given range.


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc