在计算机程序设计艺术中approximatelyEqual和essentiallyEqual差异 [英] Difference among approximatelyEqual and essentiallyEqual in The art of computer programming

查看:291
本文介绍了在计算机程序设计艺术中approximatelyEqual和essentiallyEqual差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这个code段从一些别的地方。据站长,在code从<拾取href="http://books.google.ca/books?ei=KRkLSYLZEJ7ktQOX3-ChBQ&id=T89QAAAAMAAJ&dq=%22essentially+equal%22+%22approximately+equal%22+knuth&q=%22essentially+equal%22+%22approximately+equal%22+%22definitely+less+than%22&pgis=1#search"相对=nofollow>计算机编程由克努特

由于我没有这本书的副本,可我知道什么是两个功能之间的区别是什么?

 布尔approximatelyEqual(浮起,浮动B,浮动小量)
{
    返回晶圆厂(A  -  B)&LT; =((晶圆厂(一)LT;晶圆厂(二)晶圆厂(二):晶圆厂(一))*小量?);
}

布尔essentiallyEqual(浮起,浮动B,浮动小量)
{
    返回晶圆厂(A  -  B)&LT; =((晶圆厂(一)&GT;晶圆厂(二)晶圆厂(二):晶圆厂(一))*小量?);
}
 

解决方案

要举一个例子:

 双A = 95.1,B = 100.0;
断言(approximatelyEqual(A,B,0.05));
断言(essentiallyEqual(A,B,0.05)!);
 

即,小量为5%,95.1是约100,因为它落在100值(最大)的5%的范围之内。另一方面,95.1没有本质100中,100是不从95.1 5%的差异(最小值)内。

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);
}

解决方案

To give an example:

double a = 95.1, b = 100.0;
assert( approximatelyEqual( a, b, 0.05 ) );
assert( !essentiallyEqual( a, b, 0.05 ) );

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和essentiallyEqual差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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