|Think about Loose Coupling|
adding numbers and floating point errorsby smeenz (Sexton)
|on Nov 22, 2006 at 21:24 UTC||Need Help??|
smeenz has asked for the
wisdom of the Perl Monks concerning the following question:
Today I discovered that floating point errors seem to be much more of a problem than I had anticipated.
Specifically, it seems that if I set up a simple loop to add 0.05 to a variable and then display the result, it quickly goes wrong.
For example, the following code:
which is... okayish.. because the errors only show up when I force sprintf to display to 40dp... the problem is that even though I'm only adding 0.05 (and not 0.00000000000000000000000005), the error still creeps into the results pretty quickly.
If I change the loop to run from 0 to 4, which is 100 interations, perl tells me at iteration 74 that 3.65 + 0.05 = 3.69999999999999.
I'm not sure what to think of this.. I wouldn't have expected that adding 0.05 to a number 74 times would start to produce errors as soon as the 1st decimal place.