从这里看来的。QuakeIII自然就是传奇高手卡马克的杰作之一了。在有的CPU上,这个函数比普通的(float)(1.0/sqrt(x)快4倍!快的原因之一是用了一个神秘常数,0x5f3759df。普渡大学的Chris Lomont在这篇论文里讨论了这个常数的意义,尝试用严格的方法推导出这个常数(他还提到有人认为这个函数是在NVidia工作过的Gary Tarolli写的)。Chris推出的常数是0x5f37642f),和Q_rsqrt里的稍有不同,而且实际表现也稍有不如。卡马克到底怎么推出这个常数的就是谜了。这种高手不写书,实在可惜。 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