Best way of checking if a floating point is an integer

后端 未结 12 1968
陌清茗
陌清茗 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:43

    Some other options to consider (different compilers / libraries may produce different intrinsic sequences for these tests and be faster/slower):

    bool is_int(float f) { return floor(f) == f; }
    

    This is in addition to the tests for overflow you have...

    If you are looking to really optimize, you could try the following (works for positive floats, not thoroughly tested): This assumes IEEE 32-bit floats, which are not mandated by the C++ standard AFAIK.

    bool is_int(float f)
    {
        const float nf = f + float(1 << 23);
        const float bf = nf - float(1 << 23);
        return f == bf;
    }
    

提交回复
热议问题