Best way of checking if a floating point is an integer

后端 未结 12 2009
陌清茗
陌清茗 2020-12-25 13:07

[There are a few questions on this but none of the answers are particularly definitive and several are out of date with the current C++ standard].

My research shows

12条回答
  •  青春惊慌失措
    2020-12-25 13:42

    First of all, I want to see if I got your question right. From what I've read, it seems that you want to determine if a floating-point is actually simply a representation of an integral type in floating-point.

    As far as I know, performing == on a floating-point is not safe due to floating-point inaccuracies. Therefore I am proposing the following solution,

    template
    bool is_integral(F f)
    {
      return fabs(f - static_cast(f)) <= std::numeric_limits::epsilon;
    }
    

    The idea is to simply find the absolute difference between the original floating-point and the floating-point casted to the integral type, and then determine if it is smaller than the epsilon of the floating-point type. I'm assuming here that if it is smaller than epsilon, the difference is of no importance to us.

    Thank you for reading.

提交回复
热议问题