首页 > 其他 > 详细

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

时间:2014-03-23 10:08:41      阅读:261      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
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 } 
bubuko.com,布布扣

  方法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

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

 

未完待续.......

我遇到过的神奇的难以解释的算法,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/tlm1992/p/3616955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!