Comparison issue
H. S. Teoh
hsteoh at quickfur.ath.cx
Mon Mar 19 07:45:57 PDT 2012
On Mon, Mar 19, 2012 at 08:50:02AM -0400, bearophile wrote:
> James Miller:
>
> > writeln(v1 == 1); //false
> > writeln(v1 == 1.0); //false
> > writeln(v1 == 1.0f); //false
> > writeln(v1+1 == 2.0f); //true
Using == to compare floating point values is wrong. Due to the nature of
floating point computation, there's always a possibility of roundoff
error. Therefore, the correct way to compare floats is:
immutable real epsilon = 1.0e-12; // adjustable accuracy here
if (abs(y-x) < epsilon) {
// approximately equal
} else {
// not equal
}
> Maybe I'd like to deprecate and then statically forbid the use of ==
> among floating point values, and replace it with a library-defined
> function.
[...]
I agree. Using == for any floating point values is pretty much never
right. Either we should change the definition of == for floats to use
abs(y-x)<epsilon for some given epsilon value, or we should prohibit it
altogether, and force people to always write abs(y-x)<epsilon.
T
--
Never step over a puddle, always step around it. Chances are that
whatever made it is still dripping.
More information about the Digitalmars-d-learn
mailing list