isCloseTo method

bool isCloseTo(
  1. Rational other, {
  2. Rational? relativeTolerance,
  3. Rational? absoluteTolerance,
})

Checks if this Rational is close to other within the specified tolerances.

Uses the same formula as the double version for API consistency: (this - other).abs() <= max(relativeTolerance * max(this.abs(), other.abs()), absoluteTolerance)

Common tolerance values available in RationalConstants:

Implementation

bool isCloseTo(
  Rational other, {
  Rational? relativeTolerance,
  Rational? absoluteTolerance,
}) {
  final relTol = relativeTolerance ?? RationalConstants.billionth;
  final absTol = absoluteTolerance ?? RationalConstants.trillionth;
  assert(relTol >= Rational.zero, 'Relative tolerance cannot be negative');
  assert(absTol >= Rational.zero, 'Absolute tolerance cannot be negative');
  if (this == other) return true;
  final diff = (this - other).abs();
  final maxMagnitude = abs() > other.abs() ? abs() : other.abs();
  final relativeThreshold = relTol * maxMagnitude;
  final threshold = relativeThreshold > absTol ? relativeThreshold : absTol;
  return diff <= threshold;
}