I have the following code:
double x = 0;
{ ...do stuff ...}
if(x == 0){
}
I was always taught that you shouldn’t check floats for equality. Is checking to see if it is equal to zero any different?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The reason you shouldn’t check floats for equality is that floating point numbers are not perfectly precise — there’s some inaccuracy in storage with some numbers, such as those that extended too far into the mantissa and repeating decimals (note that I’m talking about repeating decimals in base 2). You can think of this imprecision as “rounding down”. The digits that extend beyond the precision of the floating-point number are truncated, effectively rounding down.
If it has not changed, it will keep that equality. However, if you change it even slightly, you probably should not use equalities, but instead a range like
(x < 0.0001 && x > -.0001).In short: as long as you’re not playing with x at a very small level, it’s OK.