Comparing Floating-Point Numbers with Bounded Accuracy - C++ Data Type

C++ examples for Data Type:float

Introduction

Compare floating-point values for equality, greater-than, or less-than 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.

Demo Code

#include <iostream>
#include <cmath>

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);
   }//from   w ww.  j  a  v  a  2  s. co m
   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;

   cout << boolalpha << (first == second) << endl;

   cout << doubleEquals(first, second, .0001) << endl;

   cout << doubleLess(first, second, .0001) << endl;

   cout << doubleGreater(first, second, .0001) << endl;

   cout << doubleLess(first, second, .0001, true) << endl;

   cout << doubleGreater(first, second, .0001, true) << endl;
}

Result


Related Tutorials