zoukankan      html  css  js  c++  java
  • 我遇到过的神奇的难以解释的算法

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

    未完待续.......

  • 相关阅读:
    2017ecjtu-summer training #4 CodeForces 731C
    HDU 1232 并查集
    2017ecjtu-summer training #3 POJ3264
    2017ecjtu-summer training #4 UESTC 30
    斑羚飞渡 贪心
    Codeforces Round #565 (Div. 3) D. Recover it!
    P3398 仓鼠找sugar lca
    P3146 [USACO16OPEN]248 dp
    P1955 [NOI2015]程序自动分析 离散化
    P2949 [USACO09OPEN]工作调度Work Scheduling 贪心
  • 原文地址:https://www.cnblogs.com/tlm1992/p/3616955.html
Copyright © 2011-2022 走看看