浮动和双重比较最有效的方法是什么? [英] What is the most effective way for float and double comparison?

查看:28
本文介绍了浮动和双重比较最有效的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较两个 double 或两个 float 值的最有效方法是什么?

What would be the most efficient way to compare two double or two float values?

仅仅这样做是不正确的:

Simply doing this is not correct:

bool CompareDoubles1 (double A, double B)
{
   return A == B;
}

但类似于:

bool CompareDoubles2 (double A, double B) 
{
   diff = A - B;
   return (diff < EPSILON) && (-diff < EPSILON);
}

似乎浪费处理.

有人知道更智能的浮点比较器吗?

Does anyone know a smarter float comparer?

推荐答案

使用任何其他建议时要格外小心.这一切都取决于上下文.

Be extremely careful using any of the other suggestions. It all depends on context.

我花了很长时间跟踪系统中的错误,该系统假定 a==b 如果 |a-b|.潜在的问题是:

I have spent a long time tracing a bugs in a system that presumed a==b if |a-b|<epsilon. The underlying problems were:

  1. 算法中的隐含假设,如果a==bb==c 那么a==c.

对以英寸为单位的线和以密耳(0.001 英寸)为单位的线使用相同的 epsilon.那是 a==b1000a!=1000b.(这就是AlmostEqual2sComplement 要求epsilon 或最大ULPS 的原因).

Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is a==b but 1000a!=1000b. (This is why AlmostEqual2sComplement asks for the epsilon or max ULPS).

对角的余弦和线的长度使用相同的 epsilon!

The use of the same epsilon for both the cosine of angles and the length of lines!

使用这样的比较函数对集合中的项目进行排序.(在这种情况下,对双精度使用内置 C++ 运算符 == 会产生正确的结果.)

Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator == for doubles produced correct results.)

就像我说的:这完全取决于上下文以及 ab 的预期大小.

Like I said: it all depends on context and the expected size of a and b.

顺便说一句,std::numeric_limits::epsilon() 是机器 epsilon".它是 1.0 和由双精度表示的下一个值之间的差值.我猜它可以在比较函数中使用,但前提是预期值小于 1.(这是对@cdv 的回答...)

BTW, std::numeric_limits<double>::epsilon() is the "machine epsilon". It is the difference between 1.0 and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)

此外,如果您基本上在 doubles 中有 int 算术(这里我们在某些情况下使用 double 来保存 int 值),您的算术将是正确的.例如 4.0/2.0 将与 1.0+1.0 相同.只要您不做导致分数 (4.0/3.0) 或超出 int 大小的操作.

Also, if you basically have int arithmetic in doubles (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example 4.0/2.0 will be the same as 1.0+1.0. This is as long as you do not do things that result in fractions (4.0/3.0) or do not go outside of the size of an int.

这篇关于浮动和双重比较最有效的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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