4 ms·
I've seen quite a lot of errors stemming up from assumptions about floating point numbers. Not sure there is a good way of handling this in the end, except exer
by yoz-y 7y ago
I've seen quite a lot of errors stemming up from assumptions about floating point numbers. Not sure there is a good way of handling this in the end, except exert caution. Even basic assumptions like f + 1 > f will have this issue.
- magicalhippo 7y agoThe problem is that in most languages, to novices floating point numbers swim like a duck, quack like a duck, but it turns out they're alligators. A good way to get around this is reading https://floating-point-gui.de/ https://floating-point-gui.de/ to weed out any preconceptions, but yeah it's difficult to steer novices there without them stepping on one of the pitfalls first.
- stephencanon 7y agoNote that f + 1 > f can also fail for integers in many languages (e.g. it does not hold for signed integers in C or C++, because the behavior is undefined when you add 1 to INT_MAX, and unsigned integers always wrap around). This particular gotcha is not unique to floating-point.
- nayuki 7y agoYes, signed overflow can make f+1 > f be false. However in C/C++, because signed overflow is undefined behavior, the compiler is perfectly allowed to simplify the expression f+1 > f to always be true.
- stephencanon 7y agoThe compiler can make that simplification, but there's no guarantee that every compiler does, so you cannot assume that it will do so; it will sometimes happen to be true in a specific compiler, but it is never true in the standardized language model (which is what programs are written against).
- yoz-y 7y agoWhich would then have the same effect as the title's article, a bug with -O0 but working with -O3
- BubRoss 7y agoIt _could_ have that effect, but it would depend on signed integers wrapping.
- kbp 7y agoUnsigned integers are still specified to wrap.
- andrepd 7y agoi+1>i breaks even for unsigneds
- nybble41 7y agoAt least for unsigned integers i+1!=i, and the only exception to i+1>i is i==UINT_MAX. For signed integers it may be undefined behavior, of course—again in just one instance—but for floating point you may have f+1==f, or (f+1)-f>1 depending on the rounding mode, for many values of f which are nowhere near the limits of the range, not to mention other oddities like (f==f)==false when f is NaN. If you code involves floating-point operations then the number of corner cases you need to test increases greatly.
- MiroF 7y agoAlthough it's at least not UB