Can we use !islessgreater(float a, float b) to check a==b given both a and b are not nan

494 views Asked by At

To check whether two floating-point variables are equal, we cannot use something like a==b. But how about using the islessgreater() function from header file?

From C++11, there are three overloads as below

bool islessgreater (float x      , float y);
bool islessgreater (double x     , double y);
bool islessgreater (long double x, long double y);

EDIT #1 I know there are some workarounds to check equality for two floating-point variables from lots of guys. For example, Floating-point Comparison From Boost How to correctly and standardly compare floats?

What I concern is that whether we could use the standard function islessgreater() in C++11 to check (float a == float b) or not? For example

int main() {

    float a = 1E-10;
    float b = 1.001E-10;

    bool res = !isnan(a) && !isnan(b) && !islessgreater(a, b);

    std::cout << std::boolalpha;

    if (res) std::cout << "a == b" << endl;
    else std::cout << "a != b" << endl;

    return 0;
}
1

There are 1 answers

4
Harshvardhan Arora On

I don't know why you have mentioned x == y does not work. The following code works perfectly in C++ to compare two floating-point variables:

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main() {
    bool result;
    float x = 5.1235;
    float y = 5.1235;
    result = x == y;
    cout << result;
    return 0;
}