x64上的快速平方根倒数

Fast Inverse Square Root on x64

本文关键字:平方根 倒数 x64      更新时间:2023-10-16

我在网上找到了http://en.wikipedia.org/wiki/Fast_inverse_square_root。它在x64上正常工作吗?有人用过认真的测试吗?

最初快速平方倒数是为32位浮点编写的,因此只要您在IEEE-754浮点表示上操作,x64体系结构就不会影响结果。

请注意,对于"双"精度浮点(64位),您应该使用另一个常量:

64位IEEE754尺寸型双。。。显示正是0x5fe6eb50c7b537a9

这里有一个双精度浮点的实现:

#include <cstdint>
double invsqrtQuake( double number )
  {
      double y = number;
      double x2 = y * 0.5;
      std::int64_t i = *(std::int64_t *) &y;
      // The magic number is for doubles is from https://cs.uwaterloo.ca/~m32rober/rsqrt.pdf
      i = 0x5fe6eb50c7b537a9 - (i >> 1);
      y = *(double *) &i;
      y = y * (1.5 - (x2 * y * y));   // 1st iteration
      //      y  = y * ( 1.5 - ( x2 * y * y ) );   // 2nd iteration, this can be removed
      return y;
  }

我做了一些测试,它似乎运行良好

是的,如果使用正确的幻数和相应的整数类型,它就可以工作。除了上面的答案之外,这里还有一个适用于doublefloat的C++11实现。条件应该在编译时进行优化。

template <typename T, char iterations = 2> inline T inv_sqrt(T x) {
    static_assert(std::is_floating_point<T>::value, "T must be floating point");
    static_assert(iterations == 1 or iterations == 2, "itarations must equal 1 or 2");
    typedef typename std::conditional<sizeof(T) == 8, std::int64_t, std::int32_t>::type Tint;
    T y = x;
    T x2 = y * 0.5;
    Tint i = *(Tint *)&y;
    i = (sizeof(T) == 8 ? 0x5fe6eb50c7b537a9 : 0x5f3759df) - (i >> 1);
    y = *(T *)&i;
    y = y * (1.5 - (x2 * y * y));
    if (iterations == 2)
        y = y * (1.5 - (x2 * y * y));
    return y;
}

至于测试,我在我的项目中使用了以下doctest:

#ifdef DOCTEST_LIBRARY_INCLUDED
    TEST_CASE_TEMPLATE("inv_sqrt", T, double, float) {
        std::vector<T> vals = {0.23, 3.3, 10.2, 100.45, 512.06};
        for (auto x : vals)
            CHECK(inv_sqrt<T>(x) == doctest::Approx(1.0 / std::sqrt(x)));
    }
#endif