c++ - 如何在没有未定义行为的情况下实现快速逆 sqrt?

标签 c++ undefined-behavior strict-aliasing

根据我对 strict aliasing rule 的了解, 此代码为 fast inverse square root将导致 C++ 中的未定义行为:

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y; // type punning
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );

    return y;
}

这段代码真的会导致 UB 吗?如果是,如何以符合标准的方式重新实现它?如果没有,为什么不呢?

假设:在调用此函数之前,我们以某种方式检查了 float 是否为 IEEE 754 32 位格式,sizeof(long)==sizeof(float) 和平台是小端的。

最佳答案

符合标准的方式是 std::memcpy . 在您指定的假设下,这应该足够符合标准。如果可能的话,任何合理的编译器都会把它变成一堆寄存器移动。此外,我们还可以使用 C++11 的 static_assert 减轻(或至少检查)您所做的一些假设。和 <cstdint> 中的固定宽度整数类型.无论如何,字节序无关紧要,因为我们在这里没有处理任何数组,如果整数类型是小端,那么浮点类型也是。

float Q_rsqrt( float number )
{
    static_assert(std::numeric_limits<float>::is_iec559, 
                  "fast inverse square root requires IEEE-comliant 'float'");
    static_assert(sizeof(float)==sizeof(std::uint32_t), 
                  "fast inverse square root requires 'float' to be 32-bit");
    float x2 = number * 0.5F, y = number;
    std::uint32_t i;
    std::memcpy(&i, &y, sizeof(float));
    i  = 0x5f3759df - ( i >> 1 );
    std::memcpy(&y, &i, sizeof(float));
    return y * ( 1.5F - ( x2 * y * y ) );
}

关于c++ - 如何在没有未定义行为的情况下实现快速逆 sqrt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405129/

相关文章:

c++ - 浮点位和严格的别名

c++ - 在 OpenCV C++ 中训练用于车牌识别的 SVM

c++ - 方法调用的括号

c++ - strcpy 中的段错误

visual-c++ - Visual C++ 支持 "strict aliasing"吗?

C++ strict-aliasing agnostic cast

c++ - SDL_MouseButtonEvent 的行为类似于 SDL_MouseMotion

c++ - 为什么 Readline 在 autoconf 中不能作为子目录工作?

c - 是 while(1); C 中未定义的行为?

c - 在分配变量时获取变量的地址是否合法?