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.