繁体   English   中英

计算平方根以实现定点函数

[英]calculating square root for implementating a fixed point function

我试图找到不动点的平方根,并使用以下计算方法使用整数算法找到平方根的近似值。 该算法在Wikipedia中进行了描述: http//en.wikipedia.org/wiki/Methods_of_computing_square_roots

uint32_t SquareRoot(uint32_t a_nInput)
{
    uint32_t op  = a_nInput;
    uint32_t res = 0;
    uint32_t one = 1uL << 30; // The second-to-top bit is set: use 1u << 14 for uint16_t type; use 1uL<<30 for uint32_t type


    // "one" starts at the highest power of four <= than the argument.
    while (one > op)
    {
        one >>= 2;
    }

    while (one != 0)
    {
        if (op >= res + one)
        {
            op = op - (res + one);
            res = res +  2 * one;
        }
        res >>= 1;
        one >>= 2;
    }
    return res;
}

但是我无法跟踪代码中发生的情况,注释// "one" starts at the highest power of four <= than the argument. 确切的意思。 有人可以提示我代码中发生了什么事以计算参数a_nInput

非常感谢

注意如何one被初始化。

uint32_t one = 1uL << 30;

那是2 301073741824 这也是4 15

这行:

    one >>= 2;

相当于

    one = one / 4;

因此,发生的事情的伪代码是:

  • one = 4 15

  • 如果one大于a_nInput

    • one = 4 14
  • 如果one仍然大于a_nInput

    • one = 4 13
  • (等等...)

最终, one 不会超过a_nInput

// "one" starts at the highest power of four less than or equal to a_nInput

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM