std.math.approxEqual, 'maxRelDiff' parameter?

Ali Çehreli acehreli at yahoo.com
Sat Dec 15 12:57:09 PST 2012


On 12/15/2012 11:01 AM, ref2401 wrote:
> What does means 'maxRelDiff' parameter?
> I looked at the source code of this method and I still didn't get it.
>
> return fabs((lhs - rhs) / rhs) <= maxRelDiff
> || maxAbsDiff != 0 && fabs(lhs - rhs) <= maxAbsDiff;
>
> In what cases can I use this parameter?

If you consider two values to be equal if the difference between them is 
1%, then you provide 0.01 as maxRelDiff. The concept of a percentage 
difference makes sense for some programs.

Sometimes you know the magnitude of the values up front (and you are 
sure of it). In such cases you can provide an absolute difference:


import std.math;

void main()
{
     // By relative difference
     assert(approxEqual(1.01, 1.015, 0.01));
     assert(approxEqual(1010, 1019, 0.01));

     // I am sure that the values are around 10 thousand and a 
difference of 10
     // is sufficient to accept them as equal:
     assert(approxEqual(9995, 10_003, 1.0, 10.0));
}

Since the concept of equality is related to precision, sometimes it 
makes more sense to use feqrel() as it returns the number of bits of the 
mantissa that the two values have equal.

Ali


More information about the Digitalmars-d-learn mailing list