c++ - 浮点相等

标签 c++ floating-point language-lawyer precision floating-point-comparison

众所周知,在比较浮点值时必须小心。通常,我们不使用 ==,而是使用一些基于 epsilon 或 ULP 的相等性测试。

但是,我想知道,有没有什么情况下,使用 == 完全没问题?

看看这个简单的片段,哪些案例可以保证成功?

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);
}

注意:我检查过 thisthis ,但它们并不涵盖(所有)我的案例。

注2:看来我必须添加一些附加信息,所以答案在实践中可能会有用:我想知道:

  • C++ 标准是怎么说的
  • 如果 C++ 实现遵循 IEEE-754 会发生什么

这是我在 current draft standard 中找到的唯一相关声明:

The value representation of floating-point types is implementation-defined. [ Note: This document imposes no requirements on the accuracy of floating-point operations; see also [support.limits]. — end note ]

那么,这是否意味着,即使是“case a)”也是实现定义的?我的意思是,l1==l1 绝对是一个浮点运算。那么,如果一个实现是“不准确的”,那么 l1==l1 可能是假的吗?


我认为这个问题不是 Is floating-point == ever OK? 的重复问题.这个问题没有解决我要问的任何情况。相同的主题,不同的问题。我想有专门针对案例 a)-d) 的答案,但我无法在重复的问题中找到答案。

最佳答案

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

当然有。一类示例是不涉及计算的用法,例如只应在更改时执行的 setter :

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);
}

另见 Is floating-point == ever OK? Is floating-point == ever OK? .

关于c++ - 浮点相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134021/

相关文章:

c - 为什么来自 C 标准工作组的文档受密码保护?

c++ - 使用许多类型转换运算符重载时模棱两可的重载

c++ - typedef 的有效使用?

go - 从指数和尾数创建 float

c++ - 浮点除法缺陷

c++ - 没有初始化器的 constexpr 静态数据成员

c++ - 为什么在提到纯右值时这里使用术语 "object"?

c++ - 以多态类型作为函数参数的 std::function 的容器

c++ - 在低内存情况下使用具有异常处理的 STL 容器

c - 关系运算符和变量