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

來源:互聯網
上載者:User

大概意思,在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畢業吧.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.