是浮点==好吗? [英] Is floating-point == ever OK?
问题描述
今天我遇到了一个我们使用的第三方软件,在他们的示例代码中有这样的行:
// 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 $> (1)的答案是:是的,有时。但它会是脆弱的,这导致了答案(2):不。不要这样做。 对于 长话短说,即使 对我来说, *对于小值的never。 Just today I came across a third party software we're using and in their sample code there was something along these lines: I'm aware of the problem with floating-points and their representation, but it made me wonder if there are cases where Also, what about a call like There are two ways to answer this question: 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 Long story short, even though To my mind, *For small values of never. 这篇关于是浮点==好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
code>给出正确的结果?
float == float
foo(BAR)
的调用, :在特定情况下,比较将返回true,但是当你写 foo
时,你不知道(并且不应该依赖)它是如何被调用的。例如,调用 foo(BAR)
会很好,但 foo(BAR * 2.0 / 2.0)
foo(BAR * 1.0)
取决于编译器优化事情的程度)会中断。
a == b $ c $也不会依赖呼叫者执行任何算术。 c>将工作在某些情况下,你真的不应该依赖它。即使你可以保证调用语义今天也许你不能保证他们下周,所以保存自己一些痛苦,不使用
==
。
float == float
是永远不会OK,因为它几乎不可维护。
// defined in somewhere.h
static const double BAR = 3.14;
// code elsewhere.cpp
void foo(double d)
{
if (d == BAR)
...
}
float == float
would be fine? I'm not asking for when it could work, but when it makes sense and works.foo(BAR)
? Will this always compare equal as they both use the same static const BAR
?
float == float
gives the correct result?float == float
is acceptable coding?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!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 ==
.float == float
is never* OK because it's pretty much unmaintainable.