小编Sad*_*nso的帖子

将浮点值舍入到最接近的 2 的幂

虽然对于如何查找整数或浮点数的下一个 2 次方的问题有很多答案,但对于查找数字的最接近的 2 的次方却没有那么多答案。

我已经实现了以下内容:

template <typename T>
static constexpr T round_pow2(T v) {
    if constexpr (std::is_floating_point_v<T>) {
        auto high = static_cast<unsigned long>(std::ceil(v));
        auto low  = static_cast<unsigned long>(std::floor(v));

        if (high == low) {
            return round_pow2<unsigned long>(high);
        } else {
            T a = static_cast<T>(round_pow2<unsigned long>(low));
            T b = static_cast<T>(round_pow2<unsigned long>(high));

            return std::abs(a - v) <= std::abs(b - v) ? a : b;
        }
    } else {
        T high = v - 1;

        for (T i = 1; i < static_cast<T>(sizeof(T)); …
Run Code Online (Sandbox Code Playgroud)

c++ ieee-754

3
推荐指数
1
解决办法
199
查看次数

标签 统计

c++ ×1

ieee-754 ×1