Re: Floating point computations differ in different runs of same program
On 2008-02-14 16:12:24 -0500, Tim Slattery <Slattery_T@bls.gov> said:
Since floating point numbers - single or double precision - are
approximations, the == operator is not appropriate for them.
Floating-point numbers are only approximations in a very limited sense:
they don't exactly represent physical quantities, which can,
presumably, be determined to far greater precision. Once you have your
values, the operations on those floating-point numbers are completely
determinate. No approximations involved.
The problem is that programmers assume that floating-point numbers will
work just like real numbers, and when the results differ, they start
talking about approximations and randomness rather than making the
considerable effort needed to understand how floating-point works.
So, yes, if you don't know what you're doing (like most people who try
it), floating-point math gives you approximate answers. Hacking in
half-understood approximate comparisons doesn't solve this knowledge
problem.
Best way is using abs, subtraction and
less than operator with the precisions defined.
The "best" way depends on what you are trying to do. If testing for
equality is what you want to do, then operator== is the best way.
fabs(d1-d2) < 0.0001
where d1,d2 are two doubles.
This may be appropriate in some circumstances, but it is not a test for
equality.
Maybe, but it's the best you can do with floating point numbers.
No, it may be the best that YOU can do, but it's by no means a
universally better approach than testing for equality. Granted,
numerical methods are hard enough that they serve as PhD thesis topics,
but that doesn't mean that a simplistic replacement for equality
testing eliminates problems. It doesn't. It just hides them.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)