isCloseTo method

bool isCloseTo(
  1. double other, {
  2. double relativeTolerance = 1e-9,
  3. double absoluteTolerance = 1e-12,
})

Checks if this double is close to the other double, considering floating-point inaccuracies.

Uses the formula recommended for robust floating-point comparison: (this - other).abs() <= max(relativeTolerance * max(this.abs(), other.abs()), absoluteTolerance)

  • relativeTolerance: Allowed difference relative to the magnitude of the numbers.
  • absoluteTolerance: Minimum allowed absolute difference, important for comparisons near zero. Assumes tolerances are non-negative.

Implementation

bool isCloseTo(
  double other, {
  double relativeTolerance = 1e-9, // Default from Python's math.isclose
  double absoluteTolerance = 1e-12, // Differs from Python's math.isclose (which is 0.0)
}) {
  assert(relativeTolerance >= 0, 'Relative tolerance cannot be negative');
  assert(absoluteTolerance >= 0, 'Absolute tolerance cannot be negative');
  if (this == other) {
    return true; // Shortcut for identical values, handles infinities
  }
  if ((this - other).isInfinite) {
    return false; // Opposite infinities are not close
  }
  return (this - other).abs() <= math.max(relativeTolerance * math.max(abs(), other.abs()), absoluteTolerance);
}