From: Lloyd Zusman Date: 2004-05-13T03:35:45+09:00 Subject: Re: Major Addition Bug? "Sean O'Dell" writes: > On Wednesday 12 May 2004 10:50, Lloyd Zusman wrote: >> "Sean O'Dell" writes: >> > >> > I had to massage my floating point math in C/C++ a lot many years >> > ago, but I always assumed it was a flaw in the MS compiler, and >> > once I got in the habit of doing it, I forgot about it. >> >> You have a basic misunderstanding of floating point math if you >> consider its rounding and truncation characteristics to be a compiler >> bug. > > This is absolutely true; I've never taken any computer class, so I > completely missed that basic information. > >> As other people have mentioned, there is a BigDecimal class in Ruby >> that behaves closer to the way that you want. > > Now that I know what it is, I'm fine with returning to old behavior > and just massaging my comparisons. One way that we were taught to do floating point comparisons is to not check for equality, but rather, to check for the result to be within a certain "delta" of the targeted value. For example: target = 1547.91 delta = 0.0005 # some suitably small (but not too small!) number result = 625.91 + 900.00 + 22.00 if (result > target - delta && result < target + delta) ... etc. ... >> Also, consider this: if you always want the computer to give you >> exact results, what should these exact results be for each of the >> following arithmetic evaluations? ... >> >> a = 1/3 > > Well, this has an infinite decimal value even in plain math. Everyone > should expect his sort of rounding problem. But the simple arithmetic > rounding error is not something you would anticipate without, say, > having a professor point your nose right at it. That's true. Most people find it counter-intuitive to think that values like 0.1 are inexact in floating point. Just as the fraction 1/3 is an infinite repeating decimal in base 10, the fraction 1/10 is also an infinite repeating decimal in base 2 (binary). It can also be shown that your number, 1547.91, is another value that doesn't have an exact floating point representation. > Anyway, thanks for the info everyone, > > Sean O'Dell I'm glad to help. And please forgive my flippant reply in my earlier message. It just seemed appropriate in response to your somewhat strident call to the Ruby community that we fix this floating point "bug". :) -- Lloyd Zusman ljz@asfast.com God bless you.