|The stupid question is the question not asked|
Re: adding numbers and floating point errorsby mattr (Curate)
|on Nov 23, 2006 at 16:57 UTC||Need Help??|
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
UPDATED:Boneheaded mistake made unusable links! Sorry. Now fixed.