isClose function
Determines whether two floating-point numbers are approximately equal.
This function checks if the absolute difference between two numbers is less than or equal to the maximum of:
- An absolute tolerance value
absTol
- A relative tolerance value
relTol
multiplied by the maximum absolute value of the inputs
This approach handles both small and large numbers appropriately.
Parameters:
a
: First floating-point number to compareb
: Second floating-point number to comparerelTol
: Relative tolerance (default: 1e-9)absTol
: Absolute tolerance (default: 1e-15)
Returns:
true
if the numbers are approximately equal,false
otherwise
Example:
print(isClose(0.1 + 0.2, 0.3)); // true
print(isClose(1e10, 1.00001e10)); // true
print(isClose(1.0, 1.1)); // false
Implementation
bool isClose(double a, double b, {double relTol = 1e-9, double absTol = 1e-15}) {
return (a - b).abs() <= max(absTol, relTol * max(a.abs(), b.abs()));
}