是浮点==好吗? [英] Is floating-point == ever OK?

查看:120
本文介绍了是浮点==好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我遇到了一个我们使用的第三方软件,在他们的示例代码中有这样的行:

  // defined in somewhere.h 
static const double BAR = 3.14;

//代码anywhere.cpp
void foo(double d)
{
if(d == BAR)
...
}



我知道浮点数及其表示的问题,不知道是否有 float == float 会好吗?



此外,如<$> 这样的调用, c $ c> foo(BAR)?这将总是比较相等,因为他们使用相同的 static const BAR

解决方案

有两种方法可以回答这个问题: $ <$ c $>
code>给出正确的结果?

  • 是否有 float == float

    (1)的答案是:是的,有时。但它会是脆弱的,这导致了答案(2):不。不要这样做。



    对于 foo(BAR)的调用, :在特定情况下,比较将返回true,但是当你写 foo 时,你不知道(并且不应该依赖)它是如何被调用的。例如,调用 foo(BAR)会很好,但 foo(BAR * 2.0 / 2.0) foo(BAR * 1.0)取决于编译器优化事情的程度)会中断。



    长话短说,即使 a == b 将工作在某些情况下,你真的不应该依赖它。即使你可以保证调用语义今天也许你不能保证他们下周,所以保存自己一些痛苦,不使用 ==



    对我来说, float == float 是永远不会OK,因为它几乎不可维护。



    *对于小值的never。


    Just today I came across a third party software we're using and in their sample code there was something along these lines:

    // defined in somewhere.h
    static const double BAR = 3.14;
    
    // code elsewhere.cpp
    void foo(double d)
    {
        if (d == BAR)
            ...
    }
    

    I'm aware of the problem with floating-points and their representation, but it made me wonder if there are cases where float == float would be fine? I'm not asking for when it could work, but when it makes sense and works.

    Also, what about a call like foo(BAR)? Will this always compare equal as they both use the same static const BAR?

    解决方案

    There are two ways to answer this question:

    1. Are there cases where float == float gives the correct result?
    2. Are there cases where float == float is acceptable coding?

    The answer to (1) is: Yes, sometimes. But it's going to be fragile, which leads to the answer to (2): No. Don't do that. You're begging for bizarre bugs in the future.

    As for a call of the form foo(BAR): In that particular case the comparison will return true, but when you are writing foo you don't know (and shouldn't depend on) how it is called. For example, calling foo(BAR) will be fine but foo(BAR * 2.0 / 2.0) (or even maybe foo(BAR * 1.0) depending on how much the compiler optimises things away) will break. You shouldn't be relying on the caller not performing any arithmetic!

    Long story short, even though a == b will work in some cases you really shouldn't rely on it. Even if you can guarantee the calling semantics today maybe you won't be able to guarantee them next week so save yourself some pain and don't use ==.

    To my mind, float == float is never* OK because it's pretty much unmaintainable.

    *For small values of never.

    这篇关于是浮点==好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆