i am trying to find the square root of a fixed point and i used the following Calculation to find an approximation of the square root using an integer algorithm. The algorithm is described in 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;
}
but i am unable to follow whats happening in the code what does the comment // "one" starts at the highest power of four <= than the argument.
exactly means. Can someone please hint me whats happening in the code to calculate the square root of the argument a_nInput
Thanks much
Note how one
is initialized.
uint32_t one = 1uL << 30;
That's 2 30 , or 1073741824
. Which is also 4 15 .
This line:
one >>= 2;
Is equivalent to
one = one / 4;
So the pseudocode for what's happening is:
one
= 4 15
if one
is more than a_nInput
one
= 4 14 if one
is still more than a_nInput
one
= 4 13 (and so on...)
Eventually, one
will not be more than a_nInput
.
// "one" starts at the highest power of four less than or equal to a_nInput
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.