Floating point equality

  • A+
Category:Languages

It is common knowledge that one has to be careful when comparing floating point values. Usually, instead of using ==, we use some epsilon or ULP based equality testing.

However, I wonder, are there any cases, when using == is perfectly fine?

Look at this simple snippet, which cases are guaranteed to succeed?

void fn(float a, float b) {     float l1 = a/b;     float l2 = a/b;      if (l1==l1) { }        // case a)     if (l1==l2) { }        // case b)     if (l1==a/b) { }       // case c)     if (l1==5.0f/3.0f) { } // case d) }  int main() {     fn(5.0f, 3.0f); } 

Note: I've checked this and this, but they don't cover (all of) my cases.

Note2: It seems that I have to add some plus information, so answers can be useful in practice: I'd like to know:

  • what the C++ standard says
  • what happens, if a C++ implementation follows IEEE-754

 


However, I wonder, are there any cases, when using == is perfectly fine?

Sure there are. One category of examples are usages that involve no computation, e.g. setters that should only execute on changes:

void setRange(float min, float max) {     if(min == m_fMin && max == m_fMax)         return;      m_fMin = min;     m_fMax = max;      // do something with min and/or max     emit rangeChanged(min, max); } 

see also https://stackoverflow.com/a/9329400/2301274 and https://stackoverflow.com/a/6721155/2301274

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: