How to compare float and double in C++?

C++Server Side ProgrammingProgramming

Comparing floats and double variables depends on what your end goal is. If you want a runnable function without going too much in details and won't have a problem in some inaccurate calculations you can use the following function −

Example

#include<iostream>
using namespace std;

// Define the error that you can tolerate
#define EPSILON 0.000001

bool areSame(double a, double b) {
   return fabs(a - b) < EPSILON;
}

int main() {
   double a = 1.005;
   double b = 1.006;
   cout << areSame(a, a);
   cout << areSame(a, b);
}

output

This will give the output −

1
0

This function takes your tolerance for error and checks if the threshold is greater than the difference between the numbers you're comparing. If you need something much more accurate, you're better off reading this excellent blog       post:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

raja
Published on 28-Feb-2018 11:39:41
Advertisements