【发布时间】: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 <= than the argument. 的注释究竟是什么意思。有人可以提示我在代码中发生了什么来计算参数的平方根a_nInput
非常感谢
【问题讨论】:
-
n <<= a等价于n *= 2^a或n = n * 2^a其中2^a是2 的次幂,n >>= a等价于n /= 2^a或n = n / 2^a其中@ 987654332@ 是 2 的次幂。 -
这里 'one >>= 2;' 所以我们需要返回 'one' 或 'res' ?
标签: c++ fixed-point square-root