+ 3

Comparing floats and doubles in C++

I want to know why the output is different when I'm comparing a float and a double. Only the values are different. Here's the code: https://code.sololearn.com/czNb74ZGL18l/#cpp

16th May 2020, 9:24 PM
CeePlusPlus
CeePlusPlus - avatar
3 ответов
+ 10
Hey there , Yeh its seems so strange but the thing is computer is still not very good at floating point numbers and uses lot of optimization and rounding for calculations using floating number that's why sometimes these equality operator doesn't work as intended The exact reason is to do with the *Machine Epsilon* Machine Epsilon is the smallest number greater than 1.0 that is not equal to 1.0 ( for example if machine Epsilon is 0.1 then you can only have 1.1 , 1.2 or so on you can not have 1.05 or something else) this is machine dependent practically it's very very small You can check the value of machine Epsilon by this expression float f; f = std::numeric_limits<float>::epsilon(); double d; d = std::numeric_limits<double>::epsilon(); So this is it . If you want to be exact and be safe Just use this function instead // Include iostream and cmath double epsilon = std::numeric_limits<double>::epsilon() bool CMP(double a, double b) { return fabs(a-b) < epsilon ; }
16th May 2020, 10:17 PM
goodbits
goodbits - avatar