liveBook · Manning

Delta-epsilon method

As explained in 100 C++ Mistakes and How to Avoid Them

The delta-epsilon method compares floating-point values by accepting a difference within a chosen tolerance rather than requiring exact equality.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains subtraction, absolute difference, epsilon selection, and precision trade-offs through a reusable function.
Examples
Uses one-third, 100.0 / 3, and a close_enough function with configurable epsilon.
What you can do after
Apply it via a close_enough function that compares absolute difference against a chosen epsilon.
How it connects
Connects floating-point approximation with absolute difference, equality comparison, and explicit type conversion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.