Floating Point, how much can I trust less than / greater than comparisons?

前端 未结 5 1358
死守一世寂寞
死守一世寂寞 2021-02-19 04:08

Let\'s say I have two floating point numbers, and I want to compare them. If one is greater than the other, the program should take one fork. If the opposite is true, it should

5条回答
  •  北海茫月
    2021-02-19 04:53

    What about less than check with an epsilon window ? if a is less than b then a can not be equal to b

    /**
     * checks whether a <= b with epsilon window
     */
    template 
    bool eq(T a, T b){
        T e = std::numeric_limits::epsilon();
        return std::fabs(a-b) <= e;
    }
    /**
     * checks whether a < b with epsilon window
     */
    template 
    bool lt(T a, T b){
         if(!eq(a,b)){ // if a < b then a != b
             return a < b;
         }
         return false;
    }
    /**
     * checks whether a <= b with epsilon window
     */
    template 
    bool lte(T a, T b){
         if(eq(a,b)){
             return true;
         }
         return a < b;
    }
    

提交回复
热议问题