Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: adding numbers and floating point errors

by mattr (Curate)
on Nov 23, 2006 at 16:57 UTC ( #585752=note: print w/replies, xml ) Need Help??

in reply to adding numbers and floating point errors

Well, I just saw the exact same question posted somewhere else a couple days ago so it is interesting you came up with the same exact question. Anyway I found some more info about it (see end of my post).

If you just print it without using sprintf, there is no problem. If you do use sprintf you are intentionally trying to see how the internal math library is working. IIRC 13 significant digits should be fine though your example looks like 15 digits. Maybe that's a 16 bit precision C float. It happens due to the math routines and IIRC that floating point numbers are generally represented in scientific notation, which means it only guarantees a fixed number of digits precision. Also shortcuts are made for speed sometimes. If you needed as many digits as you are requesting you should be using one of the modules that does that for you as other people have noted for arbitrary precision or more precision (I remember BigNum myself), PDL or others might help too.

If you had a problem showing up without using sprintf I'd be a little more worried. Conceivably a 64bit computer might be using higher precision routines in their base libraries, but I could not say myself.

Bottom line is, this is a well known artifact common to computers and is not a bug in Perl.

HOWEVER, You want to be really careful about numbers the computer spits out when you are doing anything important like financial, scientific or statistical calculations. A rounding error or something like this can get ugly. Some interesting info along here.. also I am not sure about whether there is a perl facility to (looks like Math::BigFloat would) provide access to 80 bit extended precision values.

Wikipedia on floating point addition
General Decimal Arithmetic website at IBM and the FAQ , especially the part on how many digits precision are needed for decimal arithmetic. (It says business requirements are typically 20-30 digits but interest rate calculations could require over 2000 digits.)
What Every Computer Scientist Should Know About Floating-Point Arithmetic (html) and pdf (neat.)
perlnumber (the pod on perl's numerics)

UPDATED:Boneheaded mistake made unusable links! Sorry. Now fixed.

  • Comment on Re: adding numbers and floating point errors

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://585752]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2017-05-25 11:44 GMT
Find Nodes?
    Voting Booth?