Floating point equality

前端 未结 6 2035
渐次进展
渐次进展 2021-02-02 06:27

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 test

6条回答
  •  不思量自难忘°
    2021-02-02 06:41

    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 Is floating-point == ever OK? and Is floating-point == ever OK?.

提交回复
热议问题