【发布时间】:2013-11-19 04:40:45
【问题描述】:
C++ FAQ lite "[29.17] Why doesn't my floating-point comparison work?" 推荐这个相等测试:
#include <cmath> /* for std::abs(double) */
inline bool isEqual(double x, double y)
{
const double epsilon = /* some small number such as 1e-5 */;
return std::abs(x - y) <= epsilon * std::abs(x);
// see Knuth section 4.2.2 pages 217-218
}
- 是否正确,这意味着唯一等于零的数字是
+0和-0? - 是否应该在测试零时也使用此功能,或者更确切地说是像
|x| < epsilon这样的测试?
更新
正如 Daniel Daranas 所指出的,该函数可能最好称为 isNearlyEqual(我关心的是这种情况)。
有人指出"Comparing Floating Point Numbers",我想更突出地分享。
【问题讨论】:
-
我脑子里有一句话说,永远不要测试双倍等于。只有更大或更小。
-
@user743414 在某些情况下,测试双精度等于完全没问题。例如。
if(counter > 10.0) { counter = 0.0; //dostuff }和代码中的其他地方:if(counter == 0.0){//oh I know that counter is reseted} else{//do other stuff}... -
你真正想做什么?至于问题 1,是的,唯一比较等于 +0.0(或实际上是 -0.0)的值是 +0.0 和 -0.0。但我没有看到问题中的代码暗示了这一点。
-
@relaxxx:计数器是整数。
标签: c++ floating-point