Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page