我遇到过的神奇的难以解释的算法

一. 求刚好大于某个数的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 }

 

未完待续.......

posted @ 2014-03-21 23:44  写程序的⑨  阅读(1375)  评论(5编辑  收藏  举报