浮点数可使用相等性进行比较的情况 [英] Cases where floating-point numbers are comparable using equality

查看:75
本文介绍了浮点数可使用相等性进行比较的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始讨论浮点比较.我的观点始终是不直接使用==比较两个浮点数.

有人指出这是不正确的,并且在某些情况下使用==是完全可以的. 我可以想到一些典型的情况,在这些情况下,我会以+-INF+-0的形式对IEEE 754文字进行检查,但是除此之外,我无法想到不会导致问题的情况.

所以我的问题是:使用==进行浮点比较有效的情况是什么?

解决方案

双精度浮点表示(每个数字64位)对于--2 ** 53(-+ 9,007,199,254,740,992)以下的整数是精确的.如果您使用的是浮点数,但从整数开始并对其进行整数计算,而您从未超过该限制,那么结果是准确的,并且使用==完全可以.

通常可以精确表示的数字是N/M,其中N是整数,M是2的幂.因此,如果您只是在进行涉及例如在它们达到非常大的乘数之前,也可以使用它们的1/4、1/2、3/4和整数倍.

相反,当您处理无法精确表示的数字(例如0.1)时,近似值使我得出了令人惊讶的结果.问题的根源是中间结果可能会以更高的精度存储在临时数据中,因此,公式的结果可能会有所不同,具体取决于是否将其明确地存储在内存中,并且取决于优化级别,它也可能会发生变化. >

Recently I got into a discussion about floating point comparison. My point of view was always to not compare two floating point numbers using == directly.

It was pointed out that this is not true and there are cases where using == is perfectly fine. I can think of typical cases, where I check against IEEE 754 literals, as +-INF or +-0, but apart from that, I cannot think of a case where this wouldn’t lead to problems.

So my question is: What are the cases when a floating point comparison using == is valid?

解决方案

The double-precision floating point representation (64-bit per number) is exact for integers up to -+2**53 (-+ 9,007,199,254,740,992). If you are using floating point numbers but starting from integers and doing integer computations with them and you never passed that limit then the result is exact and using == is perfectly fine.

Numbers that in general can be represented exactly are N/M where N is integer and M is a power of two. Thus if you're just doing computations involving e.g. 1/4, 1/2, 3/4 and integer multiples of them you're fine too until you reach very big multipliers.

When instead you deal with numbers that cannot be represented exactly (e.g. 0.1) the approximation introduced my lead to surprising results. One source of problems is that intermediate results may be stored in temporaries with higher precision and thus the result of a formula may be different depending on if you store it in memory explicitly or not and it may also change depending on the optimization level.

这篇关于浮点数可使用相等性进行比较的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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