计算平方根来实现一个不动点函数

calculating square root for implementating a fixed point function

本文关键字:一个 函数 平方根 实现 计算      更新时间:2023-10-16

我试图找到一个不动点的平方根,我使用以下计算找到使用整数算法的平方根的近似值。该算法在维基百科中有描述: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;

等于2301073741824。也就是415

这条线

:

    one >>= 2;

等价于

    one = one / 4;

下面的伪代码是:

  • one = 415

  • 如果one大于a_nInput

    • one = 414
  • 如果one仍然大于a_nInput

    • one = 413
  • (等等…)

最终,one 大于a_nInput

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