为什么不能在浮点类型比较通过使用memcmp()函数? [英] Why can't the floating point types compare by using memcmp() function?

查看:203
本文介绍了为什么不能在浮点类型比较通过使用memcmp()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool floatcmp(const float a, const float b)
{
    const void *p = (void*)&a;
    const void *q = (void*)&b;
    if (memcmp(p, q, sizeof(float)) == 0)
        return true;
    return false;
}

这个例子code以上,该男子说:页 memcmp(X,Y)== 0 并不意味着 X = = Y 和浮点类型往往有一个名为NAN(不是一个数字)与NaN的== NaN的是假的属性值。
但是,我改变为void类型*,我认为编译器不知道 A 是一个浮点数。

The example code is above, the man page says memcmp(x,y)==0 does not imply that x==y and floating point types often have a value called NaN (‘not a number’) with the property that NaN==NaN is false. But I change the type to void* and I think the compiler doesn't know a is a float number.

推荐答案

它们可以通过比较memcmp() - 但是,这种比较是逐字节相比较而言,它具有的没有关系,这些字节的数值间pretation。只要所有的值都是非特殊和(INF / NaN的等等的各种口味)归一化,它应该是为 确切平等可靠的测试,但有不能保证这一点,也没有任何保证,这是比任何一个正常的确切平等的测试速度更快 A == b (其中的方式有​​大约大多数小数了同样的担忧不是正好在浮点重新presentable) - 所以两个数字应该是等于没有被重新presented其浮点近似值,这样

They can be compared by memcmp() -- HOWEVER that comparison is a byte-by-byte comparison, which has no relationship to the numerical interpretation of those bytes. As long as all the values are non-special (the various flavors of Inf/NaN etc) and normalized, it should be a reliable test for exact equality, but there is no guarantee of that, nor is there any guarantee that it's any faster than a normal exact equality test a == b (which by the way has the same concerns about most fractional numbers not being exactly representable in floating point) -- so two numbers that ought to be equal aren't represented that way by their floating point approximations.

编辑:顺便说一句,这在我看来,排序可能是一个地方,一个确切的比较可能是相关的浮点数 - 如果你告诉的qsort的数字是在'平等'的以及它们的差值小于2E 的'感,那么排序将它们放在某个不确定的顺序,因此它看起来像由一个确切的平等测试给定的顺序应该是任何其他命令一样好。

As an aside, it seems to me that sorting might be the one place that an exact comparison might be relevant for floating point numbers -- if you tell qsort that the numbers are 'equal' in the 'well their difference is less than 2e' sense, then sorting will put them in some undetermined order, so it seems like the order given by an exact equality test ought to be as good as any other order.

这篇关于为什么不能在浮点类型比较通过使用memcmp()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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