The delta-epsilon method compares approximate floating-point values by measuring their difference instead of requiring exact equality. Subtract the values, take the absolute value, and treat them as equivalent when the result is smaller than a chosen epsilon. section 12.8
Mistake: comparing floating-point values with ==
A calculation such as 100.0 / 3 may not exactly match a decimal approximation such as 33.3333333333. Replace direct equality with a close_enough function. Choose epsilon for the required precision: 1e-14 is described as roughly suitable for a typical 64-bit double, while the example uses 1e-10. section 12.8
Listing 12.16 Comparing using the delta-epsilon method
bool close_enough(double value, double
target, double epsilon=1e-14) { #1
return fabs(value-target) < epsilon; #2
}
int main() {
double amount = 100.0 / 3;
std::cout << (close_enough(amount, 33.3333333333, 1e-10) ? "true" :
"false") << '\n';
return 0;
}
Shows a reusable close_enough function that compares the absolute difference with epsilon, contrasted with direct equality in b5. section 12.8
