Function std.math.approxEqual
Computes whether a values is approximately equal to a reference value, admitting a maximum relative difference, and a maximum absolute difference.
bool approxEqual(T, U, V)
(
T value,
U reference,
V maxRelDiff = 0.01,
V maxAbsDiff = 1e-05
);
Parameters
Name | Description |
---|---|
value | Value to compare. |
reference | Reference value. |
maxRelDiff | Maximum allowable difference relative to reference .
Setting to 0.0 disables this check. Defaults to 1e-2 . |
maxAbsDiff | Maximum absolute difference. This is mainly usefull
for comparing values to zero. Setting to 0.0 disables this check.
Defaults to 1e-5 . |
Returns
true
if value
is approximately equal to reference
under
either criterium. It is sufficient, when value
satisfies
one of the two criteria.
If one item is a range, and the other is a single value, then
the result is the logical and-ing of calling approxEqual
on
each element of the ranged item against the single item. If
both items are ranges, then approxEqual
returns true
if
and only if the ranges have the same number of elements and if
approxEqual
evaluates to true
for each pair of elements.
See Also
Use feqrel
to get the number of equal bits in the mantissa.
Example
assert(approxEqual(1.0, 1.0099));
assert(!approxEqual(1.0, 1.011));
assert(approxEqual(0.00001, 0.0));
assert(!approxEqual(0.00002, 0.0));
assert(approxEqual(3.0, [3, 3.01, 2.99])); // several reference values is strange
assert(approxEqual([3, 3.01, 2.99], 3.0)); // better
float[] arr1 = [ 1.0, 2.0, 3.0 ];
double[] arr2 = [ 1.001, 1.999, 3 ];
assert(approxEqual(arr1, arr2));
Example
// relative comparison depends on reference, make sure proper
// side is used when comparing range to single value. Based on
// bugzilla issue 15763
auto a = [2e-3 - 1e-5];
auto b = 2e-3 + 1e-5;
assert(a[0] .approxEqual(b));
assert(!b .approxEqual(a[0]));
assert(a .approxEqual(b));
assert(!b .approxEqual(a));
Example
assert(!approxEqual(0.0,1e-15,1e-9,0.0));
assert(approxEqual(0.0,1e-15,1e-9,1e-9));
assert(!approxEqual(1.0,3.0,0.0,1.0));
assert(approxEqual(1.00000000099,1.0,1e-9,0.0));
assert(!approxEqual(1.0000000011,1.0,1e-9,0.0));
Example
// maybe unintuitive behavior
assert(approxEqual(1000.0,1010.0));
assert(approxEqual(9_090_000_000.0,9_000_000_000.0));
assert(approxEqual(0.0,1e30,1.0));
assert(approxEqual(0.00001,1e-30));
assert(!approxEqual(-1e-30,1e-30,1e-2,0.0));
Authors
Walter Bright, Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger