Carmack的Inverse Square Root( 就是1/sqrt(x) )的函數

大概意思,在QuakeIII的源代碼裏,有1個求Inverse Square Root( 就是1/sqrt(x) )的函數,
Carmack實現的算法在有的CPU上,比正常的(float)(1.0/sqrt(x))快了4倍!(上面這個表達式裏的sqrt(x)還是直接調彙編指令fsqrt來算的!!!)

Carmack的代碼如下:

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

實際上就是Newton法迭代,但Carmack使用了一個神祕的常數,0x5f3759df,只迭代一次就求出了結果.

Purdue大學的Chris Lomont寫了一篇論文http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf,他在裏面用數學方法推導出了一個常數0x5f37642f,跟Carmack的稍有不同,效果也沒有Carmack的好.

天才就是天才啊,Carmack不過纔是high school畢業吧.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章