On 19/03/12 15:45, H. S. Teoh wrote:
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
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.
No, no, no. That's nonsense.
For starters, note that ANY integer expression which is exact, is also
exact in floating point.
Another important case is that
if (f == 0)
is nearly always correct.
> 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
> }
And this is wrong, if y and x are both small, or both large. Your
epsilon value is arbitrary.
Absolute tolerance works for few functions like sin(), but not in general.
See std.math.feqrel for a method which gives tolerance in terms of
roundoff error, which is nearly always what you want.
To summarize:
For scientific/mathematical programming:
* Usually you want relative tolerance
* Sometimes you want exact equality.
* Occasionally you want absolute tolerance
But it depends on your application. For graphics programming you
probably want absolute tolerance in most cases.