0x5f3759df__数学之美

一个数字,让多年前性能吃紧的电脑设备可以运行3D引擎——0x5f3759df

源码

0x5f3759df这个数字来自Quake-III Arena游戏的代码中的/code/game/q_math.c
它的作用是将一个数开平方并取倒,经测试这段代码比(float)(1.0/sqrt(x))快4倍:

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

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the fuck? 
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//  y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

    return y;
}

其中,注释为what the fuck的这一句代码

i = 0x5f3759df - ( i >> 1 );                // what the fuck?

就是这段精简代码的核心,再加上y = y * ( threehalfs - ( x2 * y * y ) );
两句话就完成了开方运算!而且注意到,核心那句是定点移位运算,速度极快!特别在很多没有乘法指令的RISC结构CPU上,这样做是极其高效的。
Lomont为此写下一篇论文,"Fast Inverse Square Root"
最后,给出最精简的1/sqrt()函数:

float InvSqrt(float x)
{
    float xhalf = 0.5f * x;
    int i = *(int *)&x;
    i = 0x5f3759df - (i>>1);
    x = *(float *)&i;
    x = x * (1.5f - xhalf * x * x);
    return x;
}
posted @ 2023-12-05 22:08  不想要名字  阅读(187)  评论(0)    收藏  举报