Always false float comparisons
tsbockman via Digitalmars-d
digitalmars-d at puremagic.com
Mon May 9 12:39:52 PDT 2016
On Monday, 9 May 2016 at 19:15:20 UTC, Xinok wrote:
> It's a complex issue because there isn't necessarily right or
> wrong behavior, only things that *might* be wrong. But if we
> want to truly detect all possible cases of incorrect behavior,
> then we have to be exhaustive in our checks.
We absolutely, emphatically, DO NOT want to "detect all possible
cases of incorrect behavior". Given the limited information
available to the compiler and the intractability of the Halting
Problem, the correct algorithm for doing so is this:
foreach(line; sourceCode)
warning("This line could not be proven correct.");
Only warnings with a reasonably high signal-to-noise ratio should
be implemented.
> Not necessarily. Reusing 1.3 from the original case, the
> following assertion passes:
>
> float f = 1.3;
> assert(f < 1.3);
>
> And considering we also have <= and >=, we may as well check
> all of the comparison operators.
Because of the inevitability of rounding errors, FP code
generally cannot be allowed to depend upon precise equality
comparisons to any value other than zero (even implicit ones as
in your example).
Warning about this makes sense:
float f = 1.3;
assert(f == 1.3);
Because the `==` makes it clear that the programmer's intent was
to test for equality, and that will fail unexpectedly.
On the other hand, with `<`, `>`, `<=`, and `>=`, the compiler
should generally assume that they are being used correctly, in a
way that is tolerant of small rounding errors. Doing otherwise
would cause tons of false positives in competently written FP
code.
Educating programmers who've never studied how to write correct
FP code is too complex of a task to implement via compiler
warnings. The warnings should be limited to cases that are either
obviously wrong, or where the warning is likely to be a net
positive even for FP experts.
More information about the Digitalmars-d
mailing list