Solved Error in IF function regarding comparison with decimal value
-
Hello everyone, my question arises from the following error:
float pp=0.7; if(pp==0.7){ qDebug()<<"Correcto"; }else{ qDebug()<<"Incorrecto"; }
The error is that the compilation throws me "Incorrect" even though the condition is true, making me think that the float value was not saved properly, is there any solution for this?
-
Since float var
pp
(= 0.7) and your hard coded float 0.7 could be different when using==
for comparison, better useqFuzzyCompare(float, float)
instead
https://doc.qt.io/qt-5/qtglobal.html#qFuzzyCompare-1It should work then... If not, I don't know what's going on there :)
-
@ALEX_1 you may want to look at articles (like this one or this other one) talking about float number comparison, which is not an straight forward task.
You may want to think of comparing float point numbers using some tolerance value (i.e. epsilon).
-
@ALEX_1 said in Error in IF function regarding comparison with decimal value:
The error is that the compilation throws me "Incorrect" even though the condition is true
Float or Double values are not precise, they are splitted in to fraction and exponent (cf. https://en.wikipedia.org/wiki/Floating-point_arithmetic).
if you want to compare if float or double values are equal, you have to take care about value "imprecisions".The best/easiest way is to use
qFuzzyCompare()
(cf https://doc.qt.io/qt-5/qtglobal.html#qFuzzyCompare) -
@ALEX_1 said in Error in IF function regarding comparison with decimal value:
Hello everyone, my question arises from the following error:
float pp=0.7; if(pp==0.7){ qDebug()<<"Correcto"; }else{ qDebug()<<"Incorrecto"; }
The error is that the compilation throws me "Incorrect" even though the condition is true, making me think that the float value was not saved properly, is there any solution for this?
-
@ALEX_1 said in Error in IF function regarding comparison with decimal value:
if(pp==0.7){
You compare a float with a double here. So 0.7f != 0.7 as @KroMignon and @Pablo-J-Rogina properly explained
This will evaluate to true
if (p == 0.7f) {
But even then it will not work when you do calculations before.
-
@Christian-Ehrlicher said in Error in IF function regarding comparison with decimal value:
if (p == 0.7f) {
Up-voted your answer despite spending minutes unable to find any
p
variable in any of the code posted. What is it with people's typing accuracy today...! :( -
@JonB said in Error in IF function regarding comparison with decimal value:
What is it with people's typing accuracy today
Please blame my keyboard and not me. My 'p' key don't work well but I don't know why. Even with this knowledge I sometimes miss the 'p' somewhere. Go through my latest posts and I'm sure you will find much more missing 'p's :)