in reply to Perl 5.8.x floating point representation error

An issue discussed frequently enough to warrant a spot in perlfaq4.

Put in simple terms, you cannot rely on floating point to be free of rounding errors in some of the last few digits of precision. You're out at the limits there. Different versions of Perl, different architectures, and different alignment of planetary orbits will introduce minor rounding errors as the internal binary representation of floating point numbers manifests its limitations.

I cannot explain why one version may differ from another, but can comfortably assert that this is documented and expected behavior.

Math::BigFloat is one solution. Stringification may be another solution, depending on what you're doing with the FP numbers.

Searching through an old node of mine on a similar topic I found a great link that explains the concept better than I possibly could: What Every Computer Scientist Should Know About Floating Point Arithmetic.

Enjoy!


Dave

  • Comment on Re: Perl 5.8.x floating point representation error

Replies are listed 'Best First'.
Re^2: Perl 5.8.x floating point representation error
by satish.rpr (Novice) on Jan 21, 2009 at 12:12 UTC
    thank you Dave,

    But using Math::BigFloat either did not solve my issue. BigFloat truncates after 16 digits in the exponential part and then adds zeros. Any workaround for this ?

    use Math::BigFloat;

    Math::BigFloat->accuracy(32);
    Math::BigFloat->precision(-32);
    $test = Math::BigFloat->new(0.99999999976716932);

    print $test;

    output:
    0.99999999976716900000000000000000

    but i need 0.99999999976716932

      Try it this way (notice the quotes):

      use Math::BigFloat; Math::BigFloat->accuracy(32); Math::BigFloat->precision(-32); $test = Math::BigFloat->new('0.99999999976716932'); print $test; 0.99999999976716932000000000000000

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
      my $string = "0.99999999976716932"; my $number = 0.99999999976716932; print " string = $string number = $number "; __END__ string = 0.99999999976716932 number = 0.999999999767169