2

I encountered a weird behaviour in Perl. The following subtraction should yield zero as result (which it does in Python):

print 7.6178E-01 - 0.76178
-1.11022302462516e-16

Why does it occur and how to avoid it?

P.S. Effect appears on "v5.10.0 built for x86_64-linux-gnu-thread-multi" (Ubuntu 9.04) and "v5.8.9 built for darwin-2level" (Mac OS 10.6)

3
  • Works fine for me, I get 0 (v5.8.8, Mac OSX). Jan 13, 2010 at 12:57
  • 1
    I have two Perls on this machine here - a local build of 5.8.8 that works correctly, and the one that comes built in - that exhibits your issue. Jan 13, 2010 at 13:36
  • Occurs on 5.10.1, MSWin32-x86-multi-thread as well (Strawberry Perl 5.10.1.0).
    – Robert P
    Jan 13, 2010 at 20:53

1 Answer 1

8

It's not that scientific notation affects the precision so much as the limitations of floating point notation represented in binary. See the answers to the perlfaq4. This is a problem for any language that relies on the underlying architecture for number storage.

If you need better number handling, check out the bignum pragma.

7
  • Ok, use bignum does the trick. However, I refuse to accept this behaviour as normal, regardless of any binary representation issues. Any other language handles this correctly.
    – Simon
    Jan 13, 2010 at 14:43
  • 2
    Simon - any language that isn't demonstrating these sort of issues in at least SOME corner cases is either not using the CPU floating-point instructions or is not handling floating-point numbers correctly. Unfortunately, incorrect handling of numbers is relatively normal (at leats as far as conversion between base-10 fractional numbers and floating-point numbers).
    – Vatine
    Jan 13, 2010 at 15:00
  • 3
    This answer is true, but doesn't address the question of why two different literals expressing the same number are being stored as two different representations.
    – darch
    Jan 13, 2010 at 19:03
  • 1
    I wouldn't really say David explained it, Brian. Rather, he offered some ideas about what might be true. Is his suggestion really how the compiler parses scientific-notation literals? Is it code shared by all Perl interpreters, or do some versions do it differently? Jan 13, 2010 at 20:12
  • 1
    The read code for yourself. It's all in either perl.h or numeric.c. It boils down to who implements your atof, which depends on how you compiled the source. No matter which way you compile, you're at the mercy of how the local architecture handles multiplication or division. What David M. describes is what Perl does. Jan 13, 2010 at 23:30

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.