+ 1
Why am I seeing this comment?
Is there any reason about this comment? "Comparing floating point with == or != is unsafe"
4 ответов
+ 9
Because the accuracy of such comparison involving floating points may be limited.
It is better to include a small margin for tolerance, e.g. abs(x - y) < 0.001.
P.S. referencing to @Jay's reply :
Don't use absolute error margins. Use epsilon instead.
http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
https://stackoverflow.com/questions/590822/dealing-with-accuracy-problems-in-floating-point-numbers
+ 6
Here is a good article
http://floating-point-gui.de/errors/comparison/
Hatsys answer is right but don't use absolute error margins. They could be the wrong size. Use epsilon instead.
http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
+ 6
This is a warning, and it is displayed as with floats, the == or != may not work in the way you intended it to be...
Eg : 1.2*2.0 == 2.4
This evaluates to false, as the operators +,-,*, and / return approximate values sometimes, and so, proper comparison is not possible in all cases.
So, simply ignore this warning for small programs.
You may also check if the numbers are close enough that they can be called equal:
But this will reduce accuracy as 2.7 and 2.8 are close but not equal... So use it only for operators...
bool close(double a, double b)
{
if(double(abs(a-b))<=0.1) return true;
//Try using 0.01 as well...
return false;
}
int main()
{
if(close(2.0 * 0.7 , 1.4)) cout<<"Yes, they seem equal to me"<<endl;
else cout<<"Nope, they're different"<<endl;
}
And to disable the warning so that it never gets printed in the first place, use this after the headers:
#pragma GCC diagnostic ignored "-Wfloat-equal"
+ 5
This has to due with the limitations of precision of floating point types.
You may set a float to:
float x = 1.7;
and its actual value may be 1.700001 or something similar.
So if you do a comparison such as:
x == 1.7
it may see the difference of the 1.700001 and return false. Likewise with != it may return true.
For instance, take the following program into account:
#include <iostream>
using namespace std;
int main()
{
float x = 1.7;
if(x == 1.7) {
cout << "x equals 1.7" << endl;
}
return 0;
}
You might think that it would output "x equals 1.7", but it doesn't.
At least not until you tell the compiler to treat the literal 1.7 as a float by appending the f declaration after it like so:
1.7f
if(x == 1.7f) { // add the f declaration to the literal 1.7
cout << "x equals 1.7" << endl;
}
Now the program will output "x equals 1.7"
Note that it's not usually needed when declaring the variable as the compiler already knows that it will be a float type, but is still often used that way.