最有效的方法float和double比较 [英] Most effective way for float and double comparison

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

问题描述

什么是比较最有效的方式两个浮动值?

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;
}

不过是这样的:

But something like:

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

好像浪费的处理。

Seems to waste processing.

有谁知道一个更聪明的浮动比较器?

Does anyone know a smarter float comparer?

推荐答案

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

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

我花了很长一段时间的系统$ P $追查一个错误psumed的 A == b 的,如果的 | AB |&LT;小量的。根本的问题是:

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. 隐式presumption的一种算法,如果的 A == b 乙==ç的那么的 A ==ç

使用密尔测量了同一小量用于英寸线测线(0.001英寸)。这是的 A == b 的,但是的 1000A!= 1000B 的。 (这就是为什么AlmostEqual2sComplement要求的小量或最大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).

有角的两个余弦和线的长度,使用相同的小量的!

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.)

就像我说:这一切都取决于上下文和的的预期大小和的 B

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

顺便说一句,的std :: numeric_limits的&LT;双&GT; ::小量()是机器最小。它是介于1.0和再presentable的下一个值由双差。我猜想,这可能会在比较函数中使用,但只有当预期值都小于1。

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.

另外,如果你基本上是int算术双打(这里我们使用的双打拿在某些情况下的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.

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

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