almostEqualNormRelativeD function

bool almostEqualNormRelativeD(
  1. double a,
  2. double b,
  3. double diff,
  4. double maximumError,
)

Compares two doubles and determines if they are equal within the specified maximum error.

Implementation

bool almostEqualNormRelativeD(
    double a, double b, double diff, double maximumError) {
  // If A or B are infinity (positive or negative) then
  // only return true if they are exactly equal to each other -
  // that is, if they are both infinities of the same sign.
  if (a.isInfinite || b.isInfinite) {
    return a == b;
  }

  // If A or B are a NAN, return false. NANs are equal to nothing,
  // not even themselves.
  if (a.isNaN || b.isNaN) {
    return false;
  }

  // If one is almost zero, fall back to absolute equality
  if (a.abs() < doublePrecision || b.abs() < doublePrecision) {
    return diff.abs() < maximumError;
  }

  if ((a == 0 && b.abs() < maximumError) ||
      (b == 0 && a.abs() < maximumError)) {
    return true;
  }

  return diff.abs() < maximumError * max(a.abs(), b.abs());
}