klyn.math.Math.isClose
method
public static isClose<LEFT_TYPE extends AbstractNumber, RIGHT_TYPE extends AbstractNumber>(
a as LEFT_TYPE,
b as RIGHT_TYPE,
rel_tol as Double = 1e-9,
abs_tol as Double = 0.0
) as Boolean
Description

Reports whether two real numbers are close within relative and absolute tolerances.

The comparison is equivalent to abs(a - b) <= max(rel_tol * abs(a), rel_tol * abs(b), abs_tol). Both tolerances must be non-negative. Their defaults match the conventional floating-point comparison: rel_tol = 1e-9 and abs_tol = 0.0.

Two integer operands are compared using their exact signs and magnitudes; their difference never overflows or passes through Double. In particular, zero tolerances mean exact integer equality, including beyond 2**53 and between signed and unsigned types. Relative tolerance thresholds use Double precision; their comparison to the integer distance stays exact. When either operand is floating-point, both operands are converted to Double, so large integers may be rounded in mixed calls.

IEEE 754 special values keep their normal semantics. A NaN is never close to any value, including another NaN. Positive and negative infinity are close only to the same infinity.

Parameters
ParameterDescription
aFirst number to compare.
bSecond number to compare.
rel_tolMaximum relative tolerance; defaults to 1e-9.
abs_tolMaximum absolute tolerance; defaults to 0.0.
Returns

true when the values satisfy either tolerance.

Throws
  • ValueException if either tolerance is negative.
Example
import klyn.math

assert Math.isClose(0.1 + 0.2, 0.3)
assert Math.isClose(0.0, 1e-12, abs_tol=1e-9)
assert not Math.isClose(nan, nan)
assert Math.isClose(inf, inf)
assert not Math.isClose(inf, -inf)
assert not Math.isClose(9007199254740992l, 9007199254740993l, rel_tol=0.0)