Are floating-point numbers used without an epsilon always a code-smell?

357 views Asked by At

This question is very simple. It is related to but definitely not a dupe of:

Most unpatched Tomcat webservers are vulnerable, who's at fault?

Seen the amazing amount of things that can go wrong with floating-point numbers (including, but not limited to, different results on different architectures, wrong results when used incorrectly, two denial of services crashes affecting two different languages, etc.) I'm wondering a very simple question:

Are floating-point numbers used without an epsilon always a code-smell or a spec-smell?

(that is: should floating-point number really only ever be used for scientific computation and all the rest should be done using a fixed number of bits of precision?)

2

There are 2 answers

5
Stephen Canon On

No, they are absolutely not always a code smell.

In fact, in my line of work (low-level high-performance libraries), floating-point comparisons with a tolerance are a code smell: they indicate that the programmer either does not understand floating point, or does not fully understand the numerics of the algorithm that they are implementing, which sets off big warning bells that I should be reading over the rest of the code very, very closely.

That's not to say that they should never be used. There are lots of situations (maybe even most situations) where it's the right thing to do. It's only to say that all hard-and-fast rules are stupid, this one included.


To your clarified question: "should floating-point number really only ever be used for scientific computation and all the rest should be done using a fixed number of bits of precision?"

Of course not. That would be a monstrous engineering burden, and grossly inefficient to boot. It's just as easy for an inexperienced programmer to shoot himself in the foot with integer arithmetic (overflows, division-is-truncation, out-of-bounds array access, etc, etc) as it is with floating point. Floating-point is an enormous convenience for the vast majority of programmers; if it wasn't it wouldn't be used.

As with all things, take the time to learn about your tools, and use the right tool for the job.

0
Jimmy On

sometimes there's really no need for precision. Game engines use floating points for rendering all the time. Likewise, you wouldn't do monetary computation with floats, but it's not a problem writing a graphing system with floats.

The problem comes when you conflate two different sets of data (one non-precise, one precise (or more precise)) For example, game developers often wind up using the same coordinate system for their world-coordinates as they do for the rendering, and then when the world gets huge, their single-precision floats start showing major rounding errors. The tolerance for a full global-location coordinate isn't the same as the tolerance in a 2D-local-area-to-3D-screen-space coordinate system.