almostEqualNormI function

bool almostEqualNormI(
  1. double a,
  2. double b,
  3. double diff,
  4. int decimalPlaces,
)

Compares two doubles and determines if they are equal to within the specified number of decimal places or not, using the number of decimal places as an absolute measure.

Implementation

bool almostEqualNormI(double a, double b, double diff, int decimalPlaces) {
  // 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 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;
  }

  // The values are equal if the difference between the two numbers is smaller
  // than 10^(-numberOfDecimalPlaces). We divide by two so that we have half the
  // range on each side of the numbers, e.g. if decimalPlaces == 2,
  // then 0.01 will equal between 0.005 and 0.015, but not 0.02 and not 0.00
  return diff.abs() < pow(10, -decimalPlaces) / 2.0;
}