双精度平方根有快速C或C++标准库函数吗?

Dan*_*Dan 7 c c++ double sqrt

我发现自己在打字

double foo=1.0/sqrt(...);
Run Code Online (Sandbox Code Playgroud)

很多,我听说现代处理器有内置的反平方根操作码.

是否存在C或C++标准库的反平方根函数

  1. 使用双精度浮点?
  2. 是准确的1.0/sqrt(...)吗?
  3. 和结果一样快还是快1.0/sqrt(...)

Lig*_*ica 12

不,不,没有.不是在C++中.不.


小智 5

您可以使用此函数进行更快的逆平方根计算
维基百科上有一篇关于它如何工作的文章:https : //en.wikipedia.org/wiki/Fast_inverse_square_root
还有这个算法的 C 版本。

float invSqrt( float number ){
    union {
        float f;
        uint32_t i;
    } conv;

    float x2;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    conv.f  = number;
    conv.i  = 0x5f3759df - ( conv.i >> 1 );
    conv.f  = conv.f * ( threehalfs - ( x2 * conv.f * conv.f ) );
    return conv.f;
}
Run Code Online (Sandbox Code Playgroud)