开发者

Difference among approximatelyEqual and essentiallyEqual in The art of computer programming

开发者 https://www.devze.com 2023-01-16 05:34 出处:网络
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

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开发者_JS百科, 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 gives whether the difference between a and b is smaller than the acceptable error (epsilon), determined by the larger of a or b. This means that the two values are "close enough", and we can say that they're approximately equal.

essentiallyEqual gives whether the difference between a and b is smaller than the acceptable error (epsilon), determined by the smaller of a or b. 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 the epsilon).

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.


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 to b, and b is essentially equal to c, then a is approximately equal to c (for another value of epsilon).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号