Re: accuracy when comparing doubles
On 2009-01-12 10:20:08 -0500, Jack Crenshaw <jcrens@earthlink.net> said:
Testing floating point numbers for equality is often a bad idea because
there are many potential pitfalls associated with doing so.
How's that?
Not bad. How about applying the same thing to integer numbers? After
all, someone who divides 1 by 3 and then multiplies the result by 3
might test whether the result is 1.
The point being, of course, that whether an equality test is meaningful
depends on where the numbers being compared came from. If a programmer
did something wong along the way then the result of the equality test
won't be what he naively expects it to be. The problem isn't in the
equality test, and the solution isn't avoiding equality tests: it's
doing the calculation right (for some currently unspecified meaning of
"right").
The difference between integer math and floating-point math in this
regard is that the rules for integer math are simpler, they're taught
early on, and most programmers understand them. The solution to "I
don't understand how this works" isn't "don't worry about it, just fake
it", it's "learn it".
Now, that's an extreme statement, so don't take it literally. You
shouldn't have to have a PhD in numerical methods to use floating-point
math. But far too many people try to paper over ignorance by using
fuzzy equality tests without understanding the consequences of what
they've done, and that doesn't make thier results more reliable. Fuzzy
equality has its place, but it's not a substitute for knowing what
you're doing. And an important part of knowing what your'e doing is
knowing when you're in over your head, and need help from that person
down the hall with the PhD.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)