Is checking a double for equality ever safe?

前端 未结 5 1191
时光说笑
时光说笑 2020-12-03 04:42

I have the following code:

double x = 0;

{ ...do stuff ...}

if(x == 0){

}

I was always taught that you shouldn\'t check floats for equal

5条回答
  •  一生所求
    2020-12-03 05:08

    You still shouldn't check to see if it's equal to zero. Just check to see if it's near zero.

    private final static double EPSILON = 0.00001;
    if (x + EPSILON > 0 && x - EPSILON < 0){
    ...
    }
    

提交回复
热议问题