Quake-III Arena (雷神之锤3).what the fuck?高性能sqrt算法

无意中发现了一个高性能sqrt算法。
此算法来源于Quake-III Arena (雷神之锤3),它是90年代的经典游戏之一。
后来,QUAKE的开发商遵守GPL协议,公开了QUAKE-III的源代码,让世人有幸目睹Carmack传奇的3D引擎的源码。

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
 
    #ifndef Q3_VM
    #ifdef __linux__
         assert( !isnan(y) ); // bk010122 - FPE?
    #endif
    #endif
    return y;
} 

猜你喜欢

转载自blog.csdn.net/sukeeeeeeeee/article/details/109911308
今日推荐