3.4. Comparing Floating-Point Numbers with Bounded Accuracy

Problem

You need to compare floating-point values, but you only want tests for equality, greater-than, or less-than to be concerned with a limited number of digits. For example, you want 3.33333 and 3.33333333 to show as being equal when comparing to a precision of .0001.

Solution

Write your own comparison functions that take a parameter that bounds the accuracy of the comparison. Example 3-6 shows the basic technique for such comparison functions.

Example 3-6. Comparing floating-point numbers

#include <iostream> #include <cmath> // for fabs() using namespace std; bool doubleEquals(double left, double right, double epsilon) { return (fabs(left - right) < epsilon); } bool doubleLess(double left, double right, double epsilon, bool orequal = false) { if (fabs(left - right) < epsilon) { // Within epsilon, so considered equal return (orequal); } return (left < right); } bool doubleGreater(double left, double right, double epsilon, bool orequal = false) { if (fabs(left - right) < epsilon) { // Within epsilon, so considered equal return (orequal); } return (left > right); } int main() { double first = 0.33333333; double second = 1.0 / 3.0; cout << first << endl; cout << second << endl; // Straight equalify test. Fails when you wouldn't want it to. // (boolalpha prints booleans as "true" or "false") cout << boolalpha << (first == second) << endl; // New equality. Passes as scientific app probably wants. cout << doubleEquals(first, ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.