approxEqual() 的正确用法是什么?
起初我以为我只能依靠最大相对差异,但我错了。例如,如果 a = 0.0
和 b = 0.5
,则它们的相对差为 1.0
。在这种情况下,approxEquals(lhs, rhs, maxRelDiff, maxAbsDiff) 依赖于最大绝对差来确定两个浮点数是否相等。
这两个问题是:
如果默认值(1e-2、1e-5)不够精确,如何得出新的最大相对和绝对差值对?如何选择
1e-2
和1e-5
作为默认值?例如,如果我选择1e-4
作为最大相对差值,那么最大绝对差值是多少?如何调整最大相对和绝对差值以便与
float
和double
正常工作?
At first I thought I could rely on the maximum relative difference only, but I was wrong. For example, if a = 0.0
, and b = 0.5
, their relative difference is 1.0
. In this case approxEquals(lhs, rhs, maxRelDiff, maxAbsDiff)
relies on the maximum absolute difference to determine if two floating point numbers are equal.
The two question are:
how do I come up with a new maximum relative and absolute difference pair if the default (1e-2, 1e-5) isn't precise enough? How were
1e-2
and1e-5
chosen as the default values? For example, if I choose1e-4
as my maximum relative difference, what is the maximum absolute difference?How do I adjust the maximum relative and absolute difference values to work properly with
floats
anddoubles
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查源代码给了我这个(我删除了范围的实现)
最后一行是我们需要研究的内容:
换句话说,如果数字相对相差不超过一个因子,则该函数返回 true
maxRelDiff
或 绝对 差异不超过maxAbsDiff
,因此使用
maxRelDiff
为0.01
(或1E-2
)与 2 位(十进制)位数的精度进行比较,并使用不同于 0 的
maxAbsDiff
允许考虑接近 0 的数字即使相对差异大于maxRelDiff
,也相同编辑:基本上首先决定比较需要多准确,然后根据该结果选择
maxRelDiff
决定数字在什么时候应该等于 0,然后根据注释中的示例
:这会比较接近 1 的值,因此
maxRelDiff
在此胜出并选择任何maxAbsDiff
(低于maxRelDiff
)不会改变任何比较接近 0 到 0 的值,因此 RelDiff (
fabs((lhs - rhs) / rhs)
) 将为 1 且 < code>maxAbsDiff 胜出checking the source code gives me this (I cut out the implementations for the ranges)
this last line is what we'll need to study:
in other words the function returns true if the numbers are either relatively different by no more than a factor of
maxRelDiff
OR absolutely different by no more thanmaxAbsDiff
so using a
maxRelDiff
of0.01
(or1E-2
) compares with an accuracy of 2 (decimal) digitsand using
maxAbsDiff
different from 0 allows numbers close to 0 to be considered equal even though there relative difference is greater thanmaxRelDiff
edit: basically first decide how accurate the comparison needs to be and choose your
maxRelDiff
based on that, then decide at what point should a number be equal to 0with the examples in the comments:
this compares values close to 1 so
maxRelDiff
trumps here and choosing anymaxAbsDiff
(lower thanmaxRelDiff
) wont change anythingthis compares values close to 0 to 0 so the RelDiff (
fabs((lhs - rhs) / rhs)
) will be 1 andmaxAbsDiff
trumps虽然我无法回答你原来的问题,但我个人只是使用 fabs 进行浮点比较:
Although I can't answer your original question, I personally just use
fabs
for floating-point comparisons: