Adding smallest possible float to a float

前端 未结 4 568
半阙折子戏
半阙折子戏 2020-12-23 15:55

I want to add the smallest possible value of a float to a float. So, for example, I tried doing this to get 1.0 + the smallest possible float:

float result =         


        
4条回答
  •  半阙折子戏
    2020-12-23 16:34

    To increase/decrement a floating point value by the smallest possible amount, use nextafter towards +/- infinity().

    If you just use next_after(x,std::numeric_limits::max()), the result with be wrong in case x is infinity.

    #include 
    #include 
    #include 
    
    template
    T next_above(const T& v){
        return std::nextafter(v,std::numeric_limits::infinity()) ;
    }
    template
    T next_below(const T& v){
        return std::nextafter(v,-std::numeric_limits::infinity()) ;
    }
    
    int main(){
      std::cout << "eps   : "<::epsilon()<< std::endl; // gives eps
    
      std::cout << "after : "<::infinity(),
         std::numeric_limits::infinity()) << std::endl; // gives inf
    
      // while this is probably not what you need:
      std::cout << std::nextafter(std::numeric_limits::infinity(),
         std::numeric_limits::max()) << std::endl; // gives 1.79769e+308
    
    }
    

提交回复
热议问题