我们是否应该将浮点数的相等性与 *relative* 错误进行比较? [英] Should we compare floating point numbers for equality against a *relative* error?

查看:12
本文介绍了我们是否应该将浮点数的相等性与 *relative* 错误进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经看到很多关于浮点数相等的帖子.像我们应该如何确定 x 和 y 是否相等?"这样的问题的标准答案.是

So far I've seen many posts dealing with equality of floating point numbers. The standard answer to a question like "how should we decide if x and y are equal?" is

abs(x - y) < epsilon

其中epsilon 是一个固定的,很小的常数.这是因为操作数"x 和 y 通常是一些涉及舍入误差的计算的结果,因此标准相等运算符 == 不是我们的意思,我们真正应该问的是 x 和 y 是否 关闭,不等于.

where epsilon is a fixed, small constant. This is because the "operands" x and y are often the results of some computation where a rounding error is involved, hence the standard equality operator == is not what we mean, and what we should really ask is whether x and y are close, not equal.

现在,我觉得如果 x 与 y 几乎相等",那么 x*10^20 也应该与 y*10^20 几乎相等",因为 relative 错误应该是相同的(但相对"于什么?).但有了这些大数字,上述测试就会失败,即该解决方案无法扩展".

Now, I feel that if x is "almost equal" to y, then also x*10^20 should be "almost equal" to y*10^20, in the sense that the relative error should be the same (but "relative" to what?). But with these big numbers, the above test would fail, i.e. that solution does not "scale".

你会如何处理这个问题?我们应该重新调整数字还是重新调整 epsilon?如何?(还是我的直觉错了?)

How would you deal with this issue? Should we rescale the numbers or rescale epsilon? How? (Or is my intuition wrong?)

这是一个相关问题,但我没有就像它接受的答案一样,因为 reinterpret_cast 事情对我来说似乎有点棘手,我不明白发生了什么.请尝试提供一个简单的测试.

Here is a related question, but I don't like its accepted answer, for the reinterpret_cast thing seems a bit tricky to me, I don't understand what's going on. Please try to provide a simple test.

推荐答案

这一切都取决于具体的问题领域.是的,在一般情况下使用相对误差会更正确,但它的效率可能会大大降低,因为它涉及额外的浮点除法.如果您知道问题中数字的大致比例,则可以使用绝对误差.

It all depends on the specific problem domain. Yes, using relative error will be more correct in the general case, but it can be significantly less efficient since it involves an extra floating-point division. If you know the approximate scale of the numbers in your problem, using an absolute error is acceptable.

本页概述了一些比较浮点数的技术.它还讨论了许多重要问题,例如具有次正规、无穷大和 NaN 的问题.很好读,强烈推荐通读一遍.

This page outlines a number of techniques for comparing floats. It also goes over a number of important issues, such as those with subnormals, infinities, and NaNs. It's a great read, I highly recommend reading it all the way through.

这篇关于我们是否应该将浮点数的相等性与 *relative* 错误进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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