The OpenD Programming Language

isClose

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

bool
isClose
(
T
U
V = CommonType!(FloatingPointBaseType!T, FloatingPointBaseType!U)
)
(
T lhs
,
U rhs
,
V maxRelDiff = CommonDefaultFor!(T, U)
,
V maxAbsDiff = 0.0
)

Parameters

lhs T

First item to compare.

rhs U

Second item to compare.

maxRelDiff V

Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.

maxAbsDiff V

Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.

Return Value

Type: bool

true if the two items are approximately equal 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 isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));

See Also

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

Meta