将浮点数与没有epsilon的0.0进行比较是否可以? [英] Is it ok to compare floating points to 0.0 without epsilon?
问题描述
我知道,要比较两个浮点值,需要使用一些epsilon精度,因为它们并不精确。但是,我想知道是否存在不需要我的epsilon的极端情况。
I am aware, that to compare two floating point values one needs to use some epsilon precision, as they are not exact. However, I wonder if there are edge cases, where I don't need that epsilon.
我特别想知道做某事是否总是安全的像这样:
In particular, I would like to know if it is always safe to do something like this:
double foo(double x){
if (x < 0.0) return 0.0;
else return somethingelse(x); // somethingelse(x) != 0.0
}
int main(){
int x = -3.0;
if (foo(x) == 0.0) {
std::cout << "^- is this comparison ok?" << std::endl;
}
}
我知道有更好的方式写 foo
(例如,另外返回一个标志),但是我想知道将 0.0
分配给浮点数是否一般变量,然后将其与 0.0
进行比较。
I know that there are better ways to write foo
(e.g. returning a flag in addition), but I wonder if in general is it ok to assign 0.0
to a floating point variable and later compare it to 0.0
.
或更笼统,以下比较是否总是正确?
Or more general, does the following comparison yield true always?
double x = 3.3;
double y = 3.3;
if (x == y) { std::cout << "is an epsilon required here?" << std::endl; }
当我尝试使用它时,它似乎起作用了,但可能不应该依赖那。
When I tried it, it seems to work, but it might be that one should not rely on that.
推荐答案
是的,如果返回 0.0
,则可以将其与 0.0
; 0可以精确表示为浮点值。如果返回 3.3
,则必须更加小心,因为 3.3
不能精确表示,因此从例如,使用double浮点将产生不同的值。
Yes, if you return 0.0
you can compare it to 0.0
; 0 is representable exactly as a floating-point value. If you return 3.3
you have to be a much more careful, since 3.3
is not exactly representable, so a conversion from double to float, for example, will produce a different value.
这篇关于将浮点数与没有epsilon的0.0进行比较是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!