3 ms·
cesaref's comment is not good advice, it's not advice at all, it's a snarky take on how floating point is trickier than it looks almost invariably floating-poi
by kragen 4y ago
cesaref's comment is not good advice, it's not advice at all, it's a snarky take on how floating point is trickier than it looks
almost invariably floating-point calculations end up in some kind of comparison; if they didn't we'd probably do the calculations in a galois field or something instead
even equality comparison of floats is useful; there are an abundance of seminumerical algorithms which use it correctly on the results of computations. a trivial example is computing an attractive fixpoint by iterating a function and comparing each hare result to the previous iteration and to a tortoise. you have to be especially careful about x87 extended precision here
ieee-754 requires bit-exact results for the five fundamental operations
here is an example where your 'safe' generalization is not safe:
#include <stdio.h>
int main()
{
float f = 0.7;
printf(f == 0.7 ? "ok\n" : "wtf\n");
return 0;
}
this prints 'wtf' on, for example, x86_64-linux-gnu
- shultays 4y agowell you shouldn't expect much if you are comparing floats to doubles
- spacechild1 4y agoTrue, but it's an easy mistake to make.
- tialaramex 4y agoIt's an easy mistake to make in C (and C++) because of their lackadaisical approach to type safety. In Rust if we insist we want to compare an f32 (what C would call float) to an f64 (double), the language says it doesn't have a way to do that, highlighting our mistake. If we just try to compare an f32 with value 0.7 against 0.7, the type inference concludes 0.7 is also an f32 so it's equal, and if we do the same with an f64, this time by inference 0.7 is an f64 and so again it's equal.
- spacechild1 4y agoRust's behavior makes so much more sense! IMO, implicit conversions is one of C++ biggest weaknesses. Yes, it may save some keystrokes, but it can easily lead to subtle (or not so subtle) bugs.
- kragen 4y agoagreed
- spacechild1 4y ago> almost invariably floating-point calculations end up in some kind of comparison I'm pretty sure OP meant comparison for equality, not comparison in general (which would be absurd, indeed). > even equality comparison of floats is useful That's exactly what I tried to point out. However, these are really special cases and you need to be careful and know what you are doing.
- kragen 4y agoi think he was snarkily making an absurd comment for the humor value