Re: Floating point computations differ in different runs of same
program
On Feb 14, 10:12 pm, Tim Slattery <Slatter...@bls.gov> wrote:
Richard Herring <junk@[127.0.0.1]> wrote:
In message
<7775ee7d-0bc9-4a3c-b3c9-0b015a8b2...@d70g2000hsf.googlegroups.com>,
kasthurirangan.bal...@gmail.com writes
Do not use "=="
operator for comparing doubles.
Do not offer such sweeping generalisations.
If it weren't appropriate to use operator== on doubles, the language
wouldn't supply it.
Since floating point numbers - single or double precision - are
approximations, the == operator is not appropriate for them.
That's simply false. Floating point numbers are not, in
themselves, approximations. Every floating point number
represents an exact value.
Of course, that value might be an approximation of what is
wanted. But the same thing is true for int: any value
representing the population of France, be it int or double, will
be an approximation (and in this case, double is probably just
as precise as int---maybe more so, if int's ony have 16 bits).
The problem is that double is often used as an abstraction for
real numbers. But it's not a perfect abstraction, and you have
to understand the differences, and where the abstraction fails,
if you want to use double in this way.
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.
If it's not appropriate, then its the wrong way. There are
cases where the right thing to do is compare using ==, and there
are cases where its not. And you need to understand how
floating point works, and what you are trying to do, to be able
to even begin determing whether == is appropriate in a specific
case, and if it isn't, what you should use to replace it.
(FWIW: I don't think I've ever seen a case where your example
would be appropriate.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34