approxEqual

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

  1. bool approxEqual(T lhs, U rhs, V maxRelDiff, V maxAbsDiff = 1e-5)
    bool
    approxEqual
    (
    T
    U
    V
    )
    (
    T lhs
    ,
    U rhs
    ,,
    V maxAbsDiff = 1e-5
    )
  2. bool approxEqual(T lhs, U rhs)

Parameters

lhs
Type: T

First item to compare.

rhs
Type: U

Second item to compare.

maxRelDiff
Type: V

Maximum allowable difference relative to rhs. Defaults to 1e-2.

maxAbsDiff
Type: V

Maximum absolute difference. Defaults to 1e-5.

Return Value

Type: bool

true if the two items are approximately equal under either criterium. 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.

Examples

1 assert(approxEqual(1.0, 1.0099));
2 assert(!approxEqual(1.0, 1.011));
3 float[] arr1 = [ 1.0, 2.0, 3.0 ];
4 double[] arr2 = [ 1.001, 1.999, 3 ];
5 assert(approxEqual(arr1, arr2));
6 
7 real num = real.infinity;
8 assert(num == real.infinity);  // Passes.
9 assert(approxEqual(num, real.infinity));  // Fails.
10 num = -real.infinity;
11 assert(num == -real.infinity);  // Passes.
12 assert(approxEqual(num, -real.infinity));  // Fails.
13 
14 assert(!approxEqual(3, 0));
15 assert(approxEqual(3, 3));
16 assert(approxEqual(3.0, 3));
17 assert(approxEqual([3, 3, 3], 3.0));
18 assert(approxEqual([3.0, 3.0, 3.0], 3));
19 int a = 10;
20 assert(approxEqual(10, a));

See Also

Use feqrel to get the number of equal bits in the mantissa.

Meta

Suggestion Box / Bug Report