快速开平方的算法

来源:互联网 发布:c语言中 是什么意思 编辑:程序博客网 时间:2024/04/30 01:33

找到了 一个哥们发的快速开平方的算法
和大家一起分享一下


#ifndef _fast_sqrt_18915093_h_
#define _fast_sqrt_18915093_h_

float fast_sqrt(float x);
float fast_invsqrt(float x);

inline float fast_sqrt(float x)
{
    union
    {
        int intPart;
        float floatPart;
    } convertor;

    union
    {
        int intPart;
        float floatPart;
    } convertor2;

    convertor.floatPart = x;
    convertor2.floatPart = x;
    convertor.intPart = 0x1FBCF800 + (convertor.intPart >> 1);
    convertor2.intPart = 0x5f3759df - (convertor2.intPart >> 1);
    return 0.5f*(convertor.floatPart + (x * convertor2.floatPart));
}

float fast_invsqrt (float x)
{
    float xhalf = 0.5f * x;
    int i = *(int*)&x;
    i = 0x5f3759df - (i >> 1);
    x = *(float*)&i;
    return x*(1.5f - xhalf*x*x);
}

#endif //_fast_sqrt_18915093_h_

原创粉丝点击