Compare a 32 bit float and a 32 bit integer without casting to double, when either value could be too large to fit the other type exactly

前端 未结 1 1813
死守一世寂寞
死守一世寂寞 2021-01-18 06:28

I have a 32 bit floating point f number (known to be positive) that I need to convert to 32 bit unsigned integer. It\'s magnitude might be too large to fit. Fur

相关标签:
1条回答
  • 2021-01-18 07:17

    I think your best bet is to be a bit platform specific. 2³² can be represented precisely in floating point. Check if f is too large to fit at all, and then convert to unsigned and check against m.

    const float unsigned_limit = 4294967296.0f;
    bool ok = false;
    if (f < unsigned_limit)
    {
        const auto uf = static_cast<unsigned int>(f);
        if (uf <= m)
        {
            ok = true;
        }
    }
    

    Not fond of the double comparison, but it's clear.

    If f is usually significantly less than m (or usually significantly greater), one can test against float(m)*0.99f (respectively float(m)*1.01f), and then do the exact comparison in the unusual case. That is probably only worth doing if profiling shows that the performance gain is worth the extra complexity.

    0 讨论(0)
提交回复
热议问题