Is there a fast C or C++ standard library function for double precision inverse square root?

前端 未结 7 2034
醉话见心
醉话见心 2021-01-18 01:26

I find myself typing

double foo=1.0/sqrt(...);

a lot, and I\'ve heard that modern processors have built-in inverse square root opcodes.

7条回答
  •  离开以前
    2021-01-18 02:20

    You can use this function for faster inverse square root computing
    There's an article on wikipedia on how it works: https://en.wikipedia.org/wiki/Fast_inverse_square_root
    Also there's a C version of this algorithm.

    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;
    }
    

提交回复
热议问题