I have a trivial question. It`s been on my table for 2 days now. I couldn`t solve it. I have three logical comparisons that is giving me weird results. I have added the part of the code that works and that doesn`t work. Can anyone help me in this regard. TIA.
1 2 3 4 5 6 7 8 9 10 11
//If condition is not satisfied even though x is equal to -0.002
float x = -0.002;
if(x >= -0.002){cout<<"Loops in"<<endl;}
//If condition works if I change >= to <=
float x = -0.002;
if(x <= -0.002){cout<<"Loops in"<<endl;}
//If condition works for both <= and >= if I change the type of variable from float to double
double x = -0.002;
if(x <= -0.002){cout<<"Loops in"<<endl;}
Due to rounding errors, most floating-point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored.However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.
For comparing floating-point numbers you could do the absolute difference between them and compare them to epsilon, if epsilon is higher than that difference then the numbers are most likely equal.
1 2 3 4
bool AreSame(float a, float b)
{
return abs(a - b) < std::numeric_limits<float>::epsilon(); //don't forget to include <limits> and <cmath>
}
Comparing float and double numbers is a problematic matter, there are many libraries out there that are focused on comparing floating-point numbers
leryss and JLBorges, Thank you so much for your quick reply. I suspected something same but I ended up thinking the rounding off would have been automatically taken into account wrt number of digits.