View source code
Display the source code in std/math.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.math.approxEqual

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

bool approxEqual(T, U, V) (
  T lhs,
  U rhs,
  V maxRelDiff,
  V maxAbsDiff = 1e-05
);

bool approxEqual(T, U) (
  T lhs,
  U rhs
);

Parameters

NameDescription
lhs First item to compare.
rhs Second item to compare.
maxRelDiff Maximum allowable difference relative to rhs. Defaults to 1e-2.
maxAbsDiff Maximum absolute difference. Defaults to 1e-5.

Returns

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.

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));
float[] arr1 = [ 1.0, 2.0, 3.0 ];
double[] arr2 = [ 1.001, 1.999, 3 ];
assert(approxEqual(arr1, arr2));

real num = real.infinity;
assert(num == real.infinity);  // Passes.
assert(approxEqual(num, real.infinity));  // Fails.
num = -real.infinity;
assert(num == -real.infinity);  // Passes.
assert(approxEqual(num, -real.infinity));  // Fails.

assert(!approxEqual(3, 0));
assert(approxEqual(3, 3));
assert(approxEqual(3.0, 3));
assert(approxEqual([3, 3, 3], 3.0));
assert(approxEqual([3.0, 3.0, 3.0], 3));
int a = 10;
assert(approxEqual(10, a));

Authors

Walter Bright, Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger

License

Boost License 1.0.