我遇到過的神奇的難以解釋的算法


一. 求剛好大於某個數的2的冪的數.

  即 Round up to the next highest power of 2.

  需求來源: 在開發圖形引擎的時候,一般的紋理對象的長和寬必須是2的冪. 比如128,256,1024這樣的數.

     但是我們的紋理不一定是這樣的,因此有時候需要進行紋理的補充.

  如果有人能知道該算法原理,求告知求地址

  http://graphics.stanford.edu/~seander/bithacks.html

  devised by Sean Eron Aderson

  http://graphics.stanford.edu/~seander/

  方法1:

1 int nextPowerOf2(int n) { 
2     n -= 1; 
3     n |= n >> 1; 
4     n |= n >> 2; 
5     n |= n >> 4; 
6     n |= n >> 8; 
7     n |= n >> 16; 
8     return n + 1; 
9 } 

  方法2:

    下面的函數僅在un為2的冪時返回0;

    

uint32_t is2n(uint32_t un)
{
    return un&(un-1);
}

    下面的函數返回不大於un的2的最大冪;

uint32_t max2n(uint32_t un)
{
    uint32_t mi = is2n(un);
    return mi?max2n(mi):un;
}

二. 大名鼎鼎的平方根倒數速算法

  http://zh.wikipedia.org/wiki/%E5%B9%B3%E6%96%B9%E6%A0%B9%E5%80%92%E6%95%B0%E9%80%9F%E7%AE%97%E6%B3%95

 1 float Q_rsqrt( float number )
 2 {
 3     long i;
 4     float x2, y;
 5     const float threehalfs = 1.5F;
 6  
 7     x2 = number * 0.5F;
 8     y  = number;
 9     i  = * ( long * ) &y;                       // evil floating point bit level hacking(對浮點數的邪惡位級hack)
10     i  = 0x5f3759df - ( i >> 1 );               // what the fuck?(這他媽的是怎么回事?)
11     y  = * ( float * ) &i;
12     y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration (第一次牛頓迭代)
13 //      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed(第二次迭代,可以刪除)
14  
15     return y;
16 }

 

未完待續.......


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM