Thread overview
std.math.approxEqual, 'maxRelDiff' parameter?
Dec 15, 2012
ref2401
Dec 15, 2012
bearophile
Dec 15, 2012
ref2401
Dec 15, 2012
Ali Çehreli
Dec 15, 2012
ref2401
Dec 16, 2012
js.mdnq
December 15, 2012
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?
December 15, 2012
ref2401:

> 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?

Maybe you want to use std.math.feqrel instead.

Bye,
bearophile
December 15, 2012
> Maybe you want to use std.math.feqrel instead.

that's not what i was asking about

December 15, 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
December 15, 2012
now i got it, thanks.
December 16, 2012
On Saturday, 15 December 2012 at 19:01:23 UTC, 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?


basically floating point types are not accuracy. Is 0.000001 = 0.00000000000000000000000000000001?

It all depends! floating point calculations can accumulate rounding errors which result in comparisons that should be valid are not.

Hence, it is not technically correct to compare two floating point types. Hence, the calculation above simply compares how close the two are and accepts them as == if they are within some distance of each other.