计算机编程艺术中approximateEqual和essentialEqual的区别
我从其他地方得到这个代码片段。根据网站管理员的说法,该代码选自 Knuth 的计算机编程艺术< /a>
由于我没有那本书,我可以知道这两个函数有什么区别吗?
bool approximatelyEqual(float a, float b, float epsilon)
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool essentiallyEqual(float a, float b, float epsilon)
{
return fabs(a - b) <= ( (fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
I get this code snippet from some where else. According to the webmaster, the code is picked from The art of computer programming by Knuth
Since I do not have a copy of that book, may I know what is the difference among the two functions?
bool approximatelyEqual(float a, float b, float epsilon)
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool essentiallyEqual(float a, float b, float epsilon)
{
return fabs(a - b) <= ( (fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
举个例子:
也就是说,epsilon 是 5%,95.1 大约是 100,因为它落在 100 值(最大)的 5% 范围内。另一方面,95.1 本质上并不等于 100,因为 100 与 95.1(最小值)的差异不在 5% 之内。
To give an example:
That is, with epsilon being a 5%, 95.1 is approximately 100, as it falls within the 5% margin of the 100 value (biggest). On the other hand, 95.1 is not essentially 100, as 100 is not within a 5% difference from 95.1 (smallest value).
approximatelyEqual
给出a
和b
之间的差异是否小于可接受的误差 (epsilon
),由a
或b
中较大的一个。这意味着这两个值“足够接近”,我们可以说它们近似相等。essentiallyEqual
给出了a
和b
之间的差异是否小于可接受的误差 (epsilon
),由a
或b
中较小的一个。这意味着这些值的差异小于任何计算中可接受的差异,因此它们可能实际上并不相等,但它们“本质上相等”(给定epsilon
)。这适用于我们拥有数据和“可接受的错误”率等问题。这段代码只是为您提供了这些术语的算法定义。
approximatelyEqual
gives whether the difference betweena
andb
is smaller than the acceptable error (epsilon
), determined by the larger ofa
orb
. This means that the two values are "close enough", and we can say that they're approximately equal.essentiallyEqual
gives whether the difference betweena
andb
is smaller than the acceptable error (epsilon
), determined by the smaller ofa
orb
. This means that the values differ less than the acceptable difference in any calculation, so that perhaps they're not actually equal, but they're "essentially equal" (given theepsilon
).This has applications in issues where we have data and "acceptable error" rates and such. This code just gives you an algorithmic definition of those terms.
不同之处在于,本质平等意味着近似平等,但反之则不然。所以本质平等比近似平等更强。
此外,本质相等不是传递性的,但如果
a
本质上等于b
,并且b
本质上等于c
>,则a
大约等于c
(对于 epsilon 的另一个值)。The difference is that essential equality implies approximate equality, but not vice versa. So essential equality is stronger than approximate equality.
Also essential equality is not transitive, but if
a
is essentially equal tob
, andb
is essentially equal toc
, thena
is approximately equal toc
(for another value of epsilon).