【问题标题】:calculating square root for implementating a fixed point function计算平方根以实现定点函数
【发布时间】:2013-04-01 00:52:11
【问题描述】:

我试图找到一个固定点的平方根,我使用以下计算来使用整数算法找到平方根的近似值。该算法在维基百科中有描述: 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 &lt;= than the argument. 的注释究竟是什么意思。有人可以提示我在代码中发生了什么来计算参数的平方根a_nInput

非常感谢

【问题讨论】:

  • n &lt;&lt;= a 等价于n *= 2^an = n * 2^a 其中2^a 是2 的次幂,n &gt;&gt;= a 等价于n /= 2^an = n / 2^a 其中@ 987654332@ 是 2 的次幂。
  • 这里 'one >>= 2;' 所以我们需要返回 'one' 或 'res' ?

标签: c++ fixed-point square-root


【解决方案1】:

注意one 是如何初始化的。

uint32_t one = 1uL << 30;

这是 230,或 1073741824。这也是 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

【讨论】:

  • 我猜 OP 是在问为什么“一”应该以四的最大幂
猜你喜欢
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多